Click here to Skip to main content
15,897,334 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
I am creating windows application using c# 2010, here I am using data grid view, in my data grid view having 3 columns and many more rows. I am not entered all columns, alternatively I am enter the cells value.
Ex :
Slno	mts	cm
1	2	

2		3	

3		3
Here I want how set programmatically empty data grid view cell values taken zero(0).


What I have tried:

How to set programmatically empty data grid view cell values taken zero(0).
Posted
Updated 11-Jul-16 18:48pm
Comments
Michael_Davies 11-Jul-16 12:56pm    
As data is entered; trap the CellLeave or CellValidating event and set the cells value accordingly.
Boopalslm 11-Jul-16 13:01pm    
how to set here i am using below code, but this code i am entered some values in cell[1] its also converting zero

if (dataGridView1.RowCount > 0 && dataGridView1.CurrentRow != null)
{
dataGridView1.CurrentRow.Cells[1].Value.ToString();

}

how to solve this error. I want i am skipped cells set as zero. how to create.

Michael_Davies 11-Jul-16 13:29pm    
You are looking at the Cells value not the Row, trap the CellsValidated event and check the Cells value, if it is Null set it to zero.

In your code above dataGridView1.CurrentRow.Cells[1].Value.ToString(); is an instruction to assign a value, you do not assign it anywhere and it is of no use to set the cell value and it is hard coded to only look at Cell[1].

Using the CellsValidated will give you the actual Cell the user just entered data into.

Something along these lines:

private void dataGridView1_CellValidated(System.Object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
{
if (dataGridView1.CurrentCell.IsInEditMode) {
if (dataGridView1.CurrentCell.Value == Null) {
dataGridView1.CurrentCell.Value = 0
}
}
}

Boopalslm 11-Jul-16 13:37pm    
I am write your code in cellvalidated event but empty cell not print in zero.
How to set empty cells zero.

1 solution

After binding the data call the below function to make the empty cells as 0

C#
private void MakeZeroForEmptyCells()
       {
           foreach (DataGridViewRow row in dataGridView1.Rows)
           {
               foreach (DataGridViewCell cell in row.Cells)
               {
                   string value = Convert.ToString(cell.Value);
                   cell.Value = string.IsNullOrWhiteSpace(value) ? 0 : cell.Value;
               }

           }
       }


and you shall call this function on CellValueChanged to update the data when the cell is filled with empty value.
 
Share this answer
 

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