-2

I want to check if my datagridview value stored in column[2] is empty or null.

How can I access datagridview column?

string[] row = new string[]
{ 
  Convert.ToString(dataReader[0]),
  Convert.ToString(dataReader[1]),
  Convert.ToString(dataReader[2]),
  Convert.ToString(dataReader[3])
};
dataGridView1.Rows.Add(row);
Ajnas
  • 1
  • Does this answer your question? [How to check empty and null cells in datagridview using C#](https://stackoverflow.com/questions/8255186/how-to-check-empty-and-null-cells-in-datagridview-using-c-sharp) and [Check if datagridview cell is null or empty](https://stackoverflow.com/questions/29379244/check-if-datagridview-cell-is-null-or-empty) and [C# check if datagridview column is empty](https://stackoverflow.com/questions/11047596/c-sharp-check-if-datagridview-column-is-empty) –  May 29 '21 at 05:04
  • You can check if a `cell.Value is string` and then if `string.NullOrEmpty(cell.Value)`, parsing all columns with siggested duplicated, or one or more particular row(s) like a `SelectedRows`, as needed. –  May 29 '21 at 05:14
  • Your code can reference an individual cell in a `DataGridView` like… `datagridview1.Rows[rowIndex].Cells[colIndex].Value`. You can get the `string` value by calling the cells `Value.ToString()` method… however… you should check to see if `Value` is `null` before attempting to call its `ToString` method… `if (datagridview1.Rows[rowIndex].Cells[colIndex].Value != null) {…}` – JohnG May 29 '21 at 06:04
  • If `Value` is `null`, then your code will throw an exception if you attempt to call `Value.ToString()`. If `Value` is NOT `null`, then, it could contain an empty value and can be checked like… `if (string.IsNullOrEmpty(datagridview1.Rows[rowIndex].Cells[colIndex].Value.ToString()) { ... }`. Point being, you should check and make sure `Value` is not `null` before you call its `ToString` method. – JohnG May 29 '21 at 06:05

2 Answers2

0

whit this code you can access column from your DataGridView

foreach (DataGridViewColumn col in dataGridView1.Columns)

but for checking null values you should check the cells not the column , so just add another for to count your rows and check every cells of your specific column

your code will be like this:

for (int colCounter=0 ; colCounter<dataGridView1.Columns.Count; colCounter++)
 for(int rowCounter=0 ; rowCounter<dataGridView1.Rows.Count ; rowCounter++)
   if(DataGridView1.Rows[rowCounter].Cells[colCounter].Value.tostring()==null)
    //your code
-2

I think you need to use a loop to add those data in your datagridview like this:

foreach(var data in row)
{
    dataGridView1.Rows.Add(data);
}
Andrei Solero
  • 802
  • 1
  • 4
  • 12
  • 1
    i added data like that . now i want to check each column if it is empty/null or have values. some columns are empty in my program . if it is empty or null i want to show message box – Ajnas May 29 '21 at 05:13