简体   繁体   中英

c#: how to programmatically highlight/delete rows from datagridview

i have the results of a query being dumped into a datagridview. it looks like this:

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

i need two things

  1. to be able able to programmatically delete all the rows of datagrid where the second field = 862.62 (or just delete the third row)
  2. i need to programmtically HIGHLIGHT and scroll down to the row to show the user where the first field is QC4 and the second one is 1,251.63

to be able able to programmatically delete all the rows of datagrid 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);

To delete a row at a specific index, call RemoveAt :

dataGridView1.Rows.RemoveAt(2);

i need to programmtically HIGHLIGHT and scroll down to the row to show the user where the first field is QC4 and the second one is 1,251.63

Find the row you want to select, then set the Selected property and FirstDisplayedScrollingRowIndex property:

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

This is a very basic example - it needs some work but its a point in the right direction I think.

 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;
        }
    }

I hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM