Ben Clarke
Ben Clarke

Reputation: 256

How to accept null value in GridView from C#

I have a table in my database which passes:

back to my code behind. End_Date can be null but for some reason when i am running my code i am getting an error.

Cannot set Column 'END_DATE' to be null. Please use DBNull instead.

Here is my C# Code.

Amounts = ser.GetRewardAmounts().ToList();

    dt.Columns.Add(new DataColumn("REWARD_AMOUNT_ID", typeof(int)));
    dt.Columns.Add(new DataColumn("START_DATE", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("END_DATE", typeof(DateTime)));
    dt.Columns.Add(new DataColumn("REWARD_AMOUNT", typeof(decimal)));

    foreach (var item in Amounts)
    {
        dr = dt.NewRow();

        dr[0] = item.REWARD_AMOUNT_ID;
        dr[1] = item.START_DATE;
        dr[2] = item.END_DATE;
        dr[3] = item.REWARD_AMOUNT;

        dt.Rows.Add(dr);
    }

    DataView dv = new DataView(dt);

    dg_amounts.DataSource = dv;
    dg_amounts.DataBind();

If anyone has any information on this issue, your help would be great!

Upvotes: 0

Views: 1998

Answers (2)

Maunet
Maunet

Reputation: 1

Please use this property to handle null values into grid.

Property : nulldisplaytext="xxx"

Upvotes: 0

Patko
Patko

Reputation: 4423

Actually all the information you need is already in the exception message - you are obviously trying to set a null value to a DataColumn. The problem is that DataColumn doesn't use nulls, but DBNull. So you could do it like this:

dr[2] = DCRA.END_DATE ?? DBNull.Value;

Upvotes: 2

Related Questions