speedyraz
speedyraz

Reputation: 335

to check empty or null value in a cell of datagridview

I want to check empty of null cell of datagridview . for that I am using following code , but it is flashing message even cells are filled.

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 5 || e.ColumnIndex == 6)
    {

        if (dataGridView1.CurrentCell.Value == null ||
            dataGridView1.CurrentCell.Value == DBNull.Value ||
            String.IsNullOrWhiteSpace(dataGridView1.CurrentCell.Value.ToString()))           
        {
            MessageBox.Show("Please enter  value");
        }
    }

}

where is mistake ..

thanks in advance ...

Upvotes: 1

Views: 5016

Answers (3)

Jegan
Jegan

Reputation: 1237

The 'CellLeave' event will be fired every time you navigate from a cell, and if you have not entered into a cell, then you will not get an 'leave' event on that cell.

If you want to check a edited cell is not empty then you may want to use the 'CellEndEdit' event.

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

            if (cell.Value == null || string.IsNullOrWhiteSpace(cell.Value.ToString()))
            {
                MessageBox.Show("Please enter some velue in cell");
            }
        }

Upvotes: 1

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

From MSDN :

Occurs when a cell loses input focus and is no longer the current cell.

This mean that dataGridView1.CurrentCell is no longer the cell you want.

To get the correct cell use:

dataGridView1[e.ColumnIndex, e.RowIndex]

Upvotes: 0

EpicKip
EpicKip

Reputation: 4043

Firstly you are checking 2 different things:

e.ColumnIndex and CurrentCell

Its best to use only 1 of those so CurrentCell could be replaced by:

dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]

So the full code becomes:

if ((e.ColumnIndex == 5 || e.ColumnIndex == 6) && e.RowIndex != -1)
{
    var cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

    if (cellValue == null || cellValue == DBNull.Value 
     || String.IsNullOrWhiteSpace(cellValue.ToString()))
    {
        MessageBox.Show("Please enter  value");
    }
}

Note: the CellLeave event triggers when you (you guessed it) leave a cell (select another, deselect, whatever). So the e.ColumnIndex/RowIndex is different from the CurrentCell as you just left it. If you want to check on click, just use the click event handler.

Upvotes: 1

Related Questions