Ashish
Ashish

Reputation: 31

how to show blank instead of 0 in datagridview c#.net

I am working on a window application Visual Studio 2010 and SQL Server 2008. My code is working fine. I need only one thing that if any value is 0.000 in database, it should be shown blank in DataGridView. Please, give me solution. Thanks in advance. Code is given below:

sda = new SqlDataAdapter("select Item, Cast (Val1 AS DECIMAL (10,3)), Cast (Val2 AS DECIMAL (10,2)), Cast (Val3 AS DECIMAL (10,2)), Cast (Val4 AS DECIMAL (10,3)), sno from Opstk where Vno ='" + txtVno.Text + "'",  con);
        DataTable dt = new DataTable();
        sdaq.Fill(dt);

        dataGridView1.Rows.Clear();
        foreach (DataRow item in dt.Rows)
        {
            int n = dataGridView1.Rows.Add();
            dataGridView1.Rows[n].Cells[0].Value = item["Item"].ToString();
            dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
            dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
            dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
            dataGridView1.Rows[n].Cells[4].Value = item[4].ToString();
            dataGridView1.Rows[n].Cells[5].Value = item[5].ToString();

        }

Upvotes: 1

Views: 5766

Answers (3)

Bobby
Bobby

Reputation: 145

If the value of the grid cell is 0, but you don't want it to display 0, you can set the value of the cell to DBNull.Value

if( item[1] == 0 ) 
{
    dataGridView1.Rows[n].Cells[1].Value = DBNull.Value;
}

Later, if you need the 0 value for a calculation, you can reverse

int myValue = 0;
if (dataGridView1.Rows[n].Cells[1].Value != DBNull.Value) 
    { myValue = dataGridView1.Rows[n].Cells[1].Value; }

Upvotes: 1

TaW
TaW

Reputation: 54433

All you need to do is set a Format for either the DataGridView's global DefaultCellStyle , maybe like this:

dataGridView1.DefaultCellStyle.Format = "###.##";

or for the one of a certain column

dataGridView1.Columns[yourColumn].DefaultCellStyle.Format = "###.##";

Note however that you are adding the values not as numbers but as strings. This is not necessarily wrong, but it will prevent doing calculations and other things. It will also prevent a numeric format like above to work.

Either add them as numbers (recommended) or simply use the format you want right in the ToString function:

dataGridView1.Rows[n].Cells[1].Value = item[1].ToString("###.##");

But again: Now the numbers are lost and you would have to waste time if you ever want to use them..

Of course you may want to pick some other numeric format string..

Upvotes: 1

Dominik S
Dominik S

Reputation: 186

You can try this:
double value = Convert.ToDouble(item["Item"]); dataGridView1.Rows[n].Cells[0].Value = value == 0 ? "" : value.ToString(); But this is dirty, you should call datagridView1.DataSource = yourDataTable;

Upvotes: 0

Related Questions