0

使用文本框在给定的 datagridview 列中搜索值,下面的代码将所选行定位在包含输入文本的列上。

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        //if (Char.IsLetter(e.KeyChar))
        //{
            for (int i = 0; i < (productDataGridView.Rows.Count); i++)
            {

                if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))
                {
                    productDataGridView.FirstDisplayedCell = productDataGridView[1, i];
                    productDataGridView.CurrentRow.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                    return; // stop looping 
                }
            }
     }

问题是在文本框中输入时我无法突出显示或更改所需行的背景颜色,请问有什么帮助吗?

4

2 回答 2

0

试试这个

      //restore backcolor of rows to default e.g. loop through grid and set backcolor to white
       foreach(DataGridViewRow row in productDataGridView.Rows)
        {
           if (row.Cells[1].Value.ToString().StartsWith(textBox1.Text, true,     CultureInfo.InvariantCulture))
            {
                //productDataGridView.FirstDisplayedCell = productDataGridView[1, i];
                row.DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                return; // stop looping 
            }
            else
              //Set backcolor to default
        }

        //return; //move return here
于 2012-07-29T17:16:57.430 回答
0

尝试了这个解决方案,这最终就像一个魅力:

            try
        {
            productDataGridView.ClearSelection();   //or restore rows backcolor to default
            for (int i = 0; i < (productDataGridView.Rows.Count); i++)
            {
                if (productDataGridView.Rows[i].Cells[1].Value.ToString().StartsWith(textBox1.Text, true, CultureInfo.InvariantCulture))
                {
                    productDataGridView.FirstDisplayedScrollingRowIndex = i;
                    productDataGridView.Rows[i].Selected = true; //It is also possible to color the row backgroud
                    return;
                }
            }
        }
        catch (Exception) 
        { 
        }
于 2012-07-29T23:01:55.367 回答