1

I need to select an entire row if a cell in column 0 contains specified value. 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!!

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

DataGridView Image

Blake Thingstad
  • 1,639
  • 2
  • 12
  • 19
KAMAL96
  • 37
  • 1
  • 3
  • 8

2 Answers2

1

The sequence contains no elements

This tells me that .First() is failing in the below code.

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;
    }
}
Blake Thingstad
  • 1,639
  • 2
  • 12
  • 19
  • throw an exception when put a value does not exist in gridview " An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe Additional information: The object reference is not defined to an instance of an object." – KAMAL96 May 29 '18 at 20:32
  • @KAMAL96 What line are you getting this error on? NullReferenceExceptions are easy to fix once you know what is null. It might be the casting to string. Instead of `((string)r.Cells["Column1"].Value).Contains(enteredText)` try `r.Cells["Column1"].Value.ToString().Contains(enteredText)`. – Blake Thingstad May 29 '18 at 21:03
  • it's same exception "NullReferenceExceptions" – KAMAL96 May 29 '18 at 21:18
  • @KAMAL96 Same as what exception? This is the first time you've mentioned a NullReferenceException. "The sequence contains no elements" would be an InvalidOperationException, not NullReferenceException. – Blake Thingstad May 29 '18 at 21:21
0

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”. I am not a LINQ expert therefore, I am guessing that when you use the following command…

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

If the enteredText is NOT found… what is .First() going to return? 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. 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.

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.

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
      }
    }
  }
}
JohnG
  • 9,259
  • 2
  • 20
  • 29
  • Thank you !!! when a put a value exist in gridview work without any problem but a put a value does not exist in gridview vs throw an exception 'System.NullReferenceException' – KAMAL96 May 30 '18 at 20:59
  • You will need to show the code you are talking about. The code I posted will not throw a `NullReferrenceException` if the cells value is null because the code is checking for this in the `if` statement with `row.Cells["Column1"].Value != null` – JohnG May 31 '18 at 00:39
  • Thank you its work perfectly this solution when i created new project – KAMAL96 May 31 '18 at 10:37