Set value of a null or Empty ROW on a gridview

Asked

Viewed 1,948 times

1

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

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

ERROR: Expected type is SINGLE (FLOAT).

  • Instead of putting row["PRECO"] = ""; experiment row["PRECO"] = null;

  • I’ve tried, can’t accept it either!

3 answers

4

Resolve to change only 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 = "";
    }
}

3

Solution 1

You can make when creating the Datatable the fields that can be empty are of the type Nullable as the case of double? to allow null

Edit: Solution 2

You make this change in RowDataBound of his 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;
    }
}

That’s another way

  • Does it accept a type for each field? Or a type for each COLUMN?

  • Each column, but I recommend using only columns that will REALLY be empty or null

1

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

Try it this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.