【问题标题】:Clarification on how to select particular row in datagrid view关于如何在 datagridview 中选择特定行的说明
【发布时间】:2013-12-04 00:18:54
【问题描述】:

使用c#,winforms

我希望用户在文本框中输入一个数字。如果数字包含在我的数据网格视图的第一列中,那么该行应该突出显示或弹出,或者数据网格视图向下滚动到它以便用户可以看到它(你们明白我的意图)

我正在讨论如何实现这一点,我正在尝试一种特定的技术,但 我收到错误:“对象引用未设置为对象的实例。” 变量 searchVal在下面我的代码的 if 语句中:

 private void button3_Click_1(object sender, EventArgs e)
    {
        String searchVal = textBox1.Text;
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {

                if (dataGridView1.Rows[i].Cells[0].Value.ToString().Contains(searchVal))
                {
                    // Also Is this how to make the row highlighted?
                    dataGridView1.Rows[i].Cells[0].Selected = true;
                }

        }
    }

【问题讨论】:

  • for the variable searchVal 是什么意思?初始化还是用Contains(searchVal)的那一行?
  • @P.Brian.Mackey Contains(searchVal)

标签: c# winforms


【解决方案1】:

您应该检查单元格的null 值,考虑到您的行中至少有一个单元格,您检查的应该是:

 if (dataGridView1.Rows[i].Cells[0].Value != null &&
     dataGridView1.Rows[i].Cells[0].Value.ToString().Contains(searchVal))

您还可以添加检查单元格计数的检查,例如:

 if (dataGridView1.Rows[i].Cells.Count > 0 &&
     dataGridView1.Rows[i].Cells[0].Value != null &&
     dataGridView1.Rows[i].Cells[0].Value.ToString().Contains(searchVal))

【讨论】:

  • 这可以作为答案谢谢,但有一个相关的问题:选择整行时如何向下滚动到它?假设选择的行在下面,用户必须滚动到它。有没有办法滚动到包含 searchVal 的特定行?
  • @Newuser 你可以使用DataGridView.FirstDisplayedScrollingRowIndex 属性msdn.microsoft.com/en-us/library/…
  • 您可以根据匹配stackoverflow.com/questions/795181/…的滚动要求点击此链接
  • @Rizwan 我尝试使用该方法,但我不知道如何正确实现它:这就是我正在尝试的:dataGridView1.Rows[i].Selected = true; dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i];但是我收到一个错误,说索引超出范围
  • 你试过 dataGridView1.FirstDisplayedScrollingRowIndex = i 吗?
【解决方案2】:

检查您的 dataGridView1 中的“添加行”选项,因为它会导致 n+1 项计数,当执行 for 时,n+1 为空,也可以使上述所有。

重新调整你需要改变的焦点

dataGridView1.Rows[i].Cells[0].Selected = true;

dataGridView1.Rows[i].Selected = true;
dataGridView1.CurrentCell = dataGridView1[0, i];
break;

因为你试图集中我猜的那一行

最好的问候

【讨论】:

  • 原来的问题解决了,但现在我有另一个问题。如何在我的代码中使用 FirstDisplayedScrollingRowIndex 属性滚动到选定的行?
  • 试试这个 dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[i].Index;
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 2013-10-08
相关资源
最近更新 更多