How to check empty and null cells in datagridview using C#

前端 未结 8 2457
太阳男子
太阳男子 2020-12-17 15:02

i am trying to check the datagridview cells for empty and null value... but i can not do it right...

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
         


        
相关标签:
8条回答
  • 2020-12-17 15:52

    I think you should use this:

    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
        for (int j = 0; j < dataGridView1.ColumnCount; j++) 
        {
            if (dataGridView1.Rows[i].Cells[j].Value == DBNull.Value)
            {
                dataGridView1.Rows[i].Cells[j].Value = "null";
            }
        }
    }
    dataGridView1.Update();
    
    0 讨论(0)
  • 2020-12-17 15:53

    Works perfect for me:

    for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
    {
        DataGridViewRow dataGridViewRow = dataGridView1.Rows[i];
    
        foreach (DataGridViewCell cell in dataGridViewRow.Cells)
        {
            string val = cell.Value as string;
            if (string.IsNullOrEmpty(val))
            {
                if (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[3].Value as string)) // If you want to check more then just one cell you could also add "&& (string.IsNullOrEmpty(dataGridView1.Rows[i].Cells[ANY NUMBER].Value as string)
                {
                    MessageBox.Show(" cell is empty");
                    return;
                    /* or to delete replace with:
                    dataGridView1.Rows.Remove(dataGridViewRow);
                    break;
                    */
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题