locked
Gridview using objectdatasource shows 0 for int column when the column is NULL RRS feed

  • Question

  • User154499744 posted

    I'm relatively new to this so not sure how much detail I need to give. So please let me know if you need more info.

    I have a gridview that uses an objectdatasource. This datasource is uses a "get" method from a class. As you might guess, the get method basically runs a select SQL from a database table. There is an integer column in this table that is allowed to be NULL. For the sake of this question, let's say the column is called PersonId.

    At first, I tried assigning the PersonId like this. Person is a class and rdr is SqlDataReader that gets the result of the select SQL.

    Person.PersonId = Convert.ToInt32(rdr["PersonId"]);

    When I did this, I got this errror: Object cannot be cast from DBNull to other types.

    So, I tried this.

    if (rdr["PersonId"] != DBNull.Value)
    {
          Person.PersonId = Convert.ToInt32(rdr["PersonId"]);
    }

    This fixes the error, but when the gridview renders, this column shows the value 0 when the value is NULL.

    Is there a way to make it show NULL, the true value in the database?

    Wednesday, December 21, 2016 3:01 PM

All replies

  • User-271186128 posted

    Hi NewKid1nTown,

    Is there a way to make it show NULL, the true value in the database?

    From your description, I you want to show “Null”, you could try to use the following methods:

    1, On the GridView rowdatabound event, you could use the FindControl method to get the PersonId, then, if the value is 0, change the value to "Null".

    More details, you could refer to this link: http://www.aspsnippets.com/Articles/Find-Access-control-inside-GridView-in-RowDataBound-and-RowCommand-events-of-ASPNet-GridView.aspx

    2. Change the PersonId data type to string. then use the following code:

    if (rdr["PersonId"] != DBNull.Value)
    {
          Person.PersonId = rdr["PersonId"].ToString();
    }
    else
    {
          Person.PersonId = "Null";
    }

    Best regards,
    Dillion

    Thursday, December 22, 2016 9:39 AM