Set value of a null or empty ROW in a gridview

1

I have a Datatable from the database and I fill in a gridview , I need to leave some ROWS blank or nothing, but the fields are numeric and do not accept string or other type.

DataTable dt = ClassesControle.CNProduto.listaProdutos(null, usuario);
            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToDouble(row["PRECO"]) == 0.0)
                    row["PRECO"] = "";
             }

ERROR: The expected type is SINGLE (FLOAT).

    
asked by anonymous 21.03.2014 / 17:06

3 answers

4

Resolve if I only change the value displayed in GridView? You could do something in the event RowDataBound :

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)    
{
    if (e.Row.Cells[0].Text == "0.00") //selecione o index correto do campo no gridView
    {
        e.Row.Cells[0].Text = "";
    }
}
    
21.03.2014 / 17:41
3

Solution 1

You can make the fields that can be empty at the time of creating the DataTable be of type Nullable as the case of double? to allow null

Edit: Solution 2

You make this change in RowDataBound of your GridView

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[e.Row.Cells.Count - 1].Text = e.Row.Cells[e.Row.Cells.Count - 1].Text == 0.00 ? string.Empty : e.Row.Cells[e.Row.Cells.Count - 1].Text;
    }
}

This is another way

    
21.03.2014 / 17:31
1

The value corresponding to the NULL of the database is: DBNull.Value .

Try this:

DataTable dt = ClassesControle.CNProduto.listaProdutos(null, usuario);
foreach (DataRow row in dt.Rows)
{
    if (Convert.ToDouble(row["PRECO"]) == 0.0)
    {
        row["PRECO"] = DBNull.Value;
    }
}
    
24.03.2014 / 00:18