简体   繁体   English

如何在c#中以编程方式选择datagridview行

[英]how to select datagridview row programmatically in c#

I need to select an entire row if a cell in column 0 contains specified value.如果第 0 列中的单元格包含指定值,我需要选择整行。 I have a TextBox and DaraGridView.when I put a value exist in gridview row selected without problem But when a put doesn't exist in gridview the program throws an exception thank you in advance!!我有一个 TextBox 和 DaraGridView。当我在 gridview 行中选择存在的值时没有问题但是当 gridview 中不存在放置时,程序会抛出异常,提前谢谢你!

private void Searchvalue_TextChanged(object sender, EventArgs e)
{
    dataGridView1.ClearSelection();
    var enteredText = (sender as TextBox).Text;
    int rowIndex = -1;

    bool tempAllowUserToAddRows = dataGridView1.AllowUserToAddRows;

    // Turn off or .Value below will throw null exception
    dataGridView1.AllowUserToAddRows = false; 
    if (enteredText != String.Empty)
    {
        DataGridViewRow row = dataGridView1.Rows
            .Cast<DataGridViewRow>()
            .Where(r => r.Cells["Column1"].Value.ToString().Contains(enteredText)).First();
        rowIndex = row.Index;
        dataGridView1.AllowUserToAddRows = tempAllowUserToAddRows;
        dataGridView1.Rows[rowIndex].Selected = true;
        dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[rowIndex].Index;
    }
}

数据网格视图图像

The sequence contains no elements该序列不包含任何元素

This tells me that .First() is failing in the below code.这告诉我.First()在下面的代码中失败了。

if (enteredText != String.Empty)
{
    DataGridViewRow row = dataGridView1.Rows
        .Cast<DataGridViewRow>()
        .Where(r => r.Cells["Column1"].Value.ToString().Contains(enteredText))
        .First();
    rowIndex = row.Index;
    dataGridView1.Rows[rowIndex].Selected = true;
}

Change it to this to avoid the exception (changed other small things too).将其更改为此以避免异常(也更改了其他小东西)。

if (!string.IsNullOrEmpty(enteredText))
{
    var row = dataGridView1.Rows
        .Cast<DataGridViewRow>()
        .FirstOrDefault(r => ((string)r.Cells["Column1"].Value).Contains(enteredText));
    if (row != null)
    {
        row.Selected = true;
    }
}

Alternatively, if you want to select all rows that contain the text...或者,如果要选择包含文本的所有行...

if (!string.IsNullOrEmpty(enteredText))
{
    var rows = dataGridView1.Rows
        .Cast<DataGridViewRow>()
        .Where(r => ((string)r.Cells["Column1"].Value).Contains(enteredText));
    foreach (var row in rows)
    {
        row.Selected = true;
    }
}

It is unclear what you are trying to accomplish here.目前尚不清楚您要在这里完成什么。 It appears to be some sort of “filter” or “selection” mechanism.它似乎是某种“过滤器”或“选择”机制。 Whatever you are trying to accomplish here… it appears you are going about this in the most difficult way.无论你想在这里完成什么……看起来你是在以最困难的方式去做这件事。

As others have pointed out this error… Sequence contains no elements?正如其他人指出的这个错误...... 序列不包含元素?

Comments and the error “clearly” states, you are getting an “InvalidOperationException”.注释和错误“清楚地”指出,您收到了“InvalidOperationException”。 I am not a LINQ expert therefore, I am guessing that when you use the following command…因此,我不是 LINQ 专家,我猜当您使用以下命令时……

Where(r => r.Cells["Column1"].Value.ToString().Contains(enteredText)).First();

If the enteredText is NOT found… what is .First() going to return?如果没有找到enteredText ... .First()会返回什么? This may be the cause of your error.这可能是导致您出错的原因。 Replacing this with a well-commented solution below may fix “this” problem.用下面评论良好的解决方案替换它可能会解决“这个”问题。

Where(r => r.Cells["Column1"].Value.ToString().Contains(enteredText)).FirstOrDefault();

FirstOrDefault() will return null if the text is not found.如果未找到文本,则FirstOrDefault()将返回 null。 This means it won't “fail” with the “InvalidOperationException” when the text is not found… however, the variable row is going to be null and the code will obliging “fail” on the very next line…this time with a null pointer exception since row will be null if the text is not found.这意味着当找不到文本时,它不会“失败”并出现“InvalidOperationException”……但是,变量row将为空,并且代码将在下一行强制“失败”……这次是空因为指针异常row将是无效的,如果没有找到的文本。

Without knowing what you are trying to do in an overall perspective I can only highly recommend that you use some sort of “collection” to store the data in the grid, most of these DataSources have built in mechanisms to help when doing things like searching/sorting etc.… It will obviously require more work from you to manage the grid data yourself.在不知道您从整体角度尝试做什么的情况下,我只能强烈建议您使用某种“集合”将数据存储在网格中,这些DataSources大多数都有内置的机制来帮助执行诸如搜索/排序等......显然需要您做更多的工作来自己管理网格数据。

Without using a data source, the code below should accomplish what you describe.在不使用数据源的情况下,下面的代码应该可以完成您所描述的内容。

private void Searchvalue_TextChanged(object sender, EventArgs e) {
  dataGridView1.ClearSelection();
  var targetText = Searchvalue.Text;
  if (targetText != String.Empty) {
    foreach (DataGridViewRow row in dataGridView1.Rows) {
      if (!row.IsNewRow && row.Cells["Column1"].Value != null && row.Cells["Column1"].Value.ToString().Contains(targetText)) {
        row.Selected = true;
        dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
        break;  // remove this if you want to select all the rows that contain the text
      }
    }
  }
}

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

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