Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when i enter data from datagridview to database it also allow null..but i wanted to prevent null value to enter in the database from gridview.in gridview i take textboxes that have 3 columns:id,name and city.if i enter id and city,datagridview allow that and does not give any error.so my question is if user put the cells blank datagridview does not allow user to move next cell untill user input in that cells
I tried some code but not work like:
C#
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            int i = dataGridView1.Rows.Count;
            for (int j = 0; j < i; j++)
            {


                if (dataGridView1.Rows[j].Cells[0].Value == null)
                {
                    MessageBox.Show("Field 1 is empty");
                }
                else if(dataGridView1.Rows[j].Cells[2].Value == null)
                {
                    MessageBox.Show("Field 2 is empty");

                }
                else if (dataGridView1.Rows[j].Cells[2].Value == null)
                {
                    MessageBox.Show("Field 3 is empty");

                }

            }

        }
Posted
Comments
Tushar sangani 22-Dec-14 1:09am    
Simply Set requiredfield Validation in those Text Box
sasanka sekhar panda 22-Dec-14 4:34am    
There is no requiredfield validator for windows application . This is not gridview ,this is dataGridView

1 solution

Here is a complete solution: How to: Validate Data in the Windows Forms DataGridView Control[^]

C#
private void dataGridView1_CellValidating(object sender,
    DataGridViewCellValidatingEventArgs e)
{
    // Validate the CompanyName entry by disallowing empty strings.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
    {
        if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            dataGridView1.Rows[e.RowIndex].ErrorText =
                "Company Name must not be empty";
            e.Cancel = true;
        }
    }
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 22-Dec-14 13:47pm    
Makes sense, a 5.
I would add that some better approach would be not creating cells with null value in first place. Also, the case of null is the simplest, because, even though cell Value can have any runtime types, it uses boxing which makes the access to this property always as to reference-type objects.
—SA
Maciej Los 22-Dec-14 13:48pm    
Thank you, Sergey ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900