C #: how to programmatically select / delete rows from datagridview

I have the results of a query dumped in a datagridview. it looks like this:

QC3 498.46
QC4 1,251.63
QC1 862.62
QC2 1,432.21

I need two things

  • to be able to programmatically delete all datagrid rows where the second field is = 862.62(or just delete the third row)
  • I need to program HIGHLIGHT and scroll down to the line to show the user where the first field QC4is and the second is1,251.63
+3
source share
2 answers

to be able to programmatically delete all datagrid rows, where the second field = 862.62

var rowsToRemove = from DataGridViewRow r in dataGridView1.Rows
                    where r.Cells[1].Value.ToString() == "862.62"  // use whatever conversion is appropriate here
                    select r;

foreach (var r in rowsToRemove)
    dataGridView1.Rows.Remove(r);

, RemoveAt:

dataGridView1.Rows.RemoveAt(2);

HIGHLIGHT , , QC4, - 1,251.63.

, , Selected FirstDisplayedScrollingRowIndex:

rowToSelect.Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = rowToSelect.Index;
+5

- - , , .

 private void Form1_Load(object sender, EventArgs e)
    {
        List<TestClass> list = new List<TestClass>();
        list.Add(new TestClass() { Prop1="QC1",Prop2="1.000"});
        list.Add(new TestClass() { Prop1 = "QC2", Prop2 = "2.000" });
        list.Add(new TestClass() { Prop1 = "QC3", Prop2 = "3.000" });
        list.Add(new TestClass() { Prop1 = "QC4", Prop2 = "4.000" });

        dataGridView1.DataSource = list;


    }

    public class TestClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }

        public TestClass()
        {

        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[0].Value == "QC3" && row.Cells[1].Value == "3.000")
                row.Selected = true;
        }
    }

, :)

+1

Source: https://habr.com/ru/post/1772884/


All Articles