简体   繁体   English

c#:如何以编程方式突出显示/删除datagridview中的行

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

i have the results of a query being dumped into a datagridview. 我有一个查询的结果被转储到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) 能够以编程方式删除第二个字段= 862.62 (或只删除第三行)的datagrid的所有行
  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 我需要以编程方式突出显示并向下滚动到该行以向用户显示第一个字段是QC4 ,第二个字段是1,251.63

to be able able to programmatically delete all the rows of datagrid where the second field = 862.62 能够以编程方式删除第二个字段= 862.62的所有datagrid行

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 : 要删除特定索引处的行,请调用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 我需要以编程方式突出显示并向下滚动到该行以向用户显示第一个字段是QC4的位置,第二个字段是1,251.63

Find the row you want to select, then set the Selected property and FirstDisplayedScrollingRowIndex property: 找到要选择的行,然后设置Selected属性和FirstDisplayedScrollingRowIndex属性:

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 :) 我希望这有帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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