0

I have a datagridview on my winform which returns a search result from my database. After the search is returned, I would like to delete null rows from an specified column. Here's an example:

enter image description here

let's say that I want to delete the rows which have null value on the type #2 column.

I am totally stuck. How should I do this?

spajce
  • 7,044
  • 5
  • 29
  • 44
Mudkip
  • 373
  • 6
  • 27
  • I've tried to modify the first answer from this link: http://stackoverflow.com/questions/2824576/how-to-remove-row-which-has-one-or-more-empty-or-null-cell the problem is that i couldn't find any option to specify a column. Any Idea? ps: this code doesn't fit for my problem because every row has a null value, so, it will delete all the records. – Mudkip Jan 20 '13 at 22:30
  • okay, is this optional or necessary to delete all the column with `null`? where do want to delete in the `datagridview` only or from `DatagridViewRow` to database? – spajce Jan 20 '13 at 22:40
  • I do not intend to delete all the rows with null in all columns, just in one (like I've said above, like Type #2 or Ability #1 - for example). And I want to deleted it directly in the datagridView, since I am not storing the search's result in any database's table. – Mudkip Jan 20 '13 at 22:48
  • try my answer.. if you have found any problem let me know :) – spajce Jan 20 '13 at 22:54

1 Answers1

1
var rowsNull = (from a in dataGridView1.Rows.Cast<DataGridViewRow>()
    where a.Cells[2].Value == null
    select a).ToList();
foreach (DataGridViewRow item in rowsNull)
{
    dataGridView1.Rows.RemoveAt(item.Index);
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
spajce
  • 7,044
  • 5
  • 29
  • 44
  • it throws the InvalidOperationException, something like "it's not possible to delete a non-confirmed row", on dataGridView1.Rows.RemoveAt(item.Index); One question: cell is actually a column or it represents a collection of rows and columns? – Mudkip Jan 21 '13 at 00:09
  • my answer is correct but you should to follow this [after removing rows](http://stackoverflow.com/questions/1560559/c-sharp-how-do-i-refresh-datagridview-after-removing-rows) or [DataGridView.Rows.RemoveAt(int index)](http://stackoverflow.com/questions/7508624/datagridview-rows-removeatint-index-doesnt-remove-row-in-windows-form) – spajce Jan 21 '13 at 00:14
  • This works perfectly for me! Thanks. Using .remove(row) didn't work properly for me. – Perfection Oct 07 '13 at 15:13