0

I have a table in my database which passes:

  • RewardAmountID
  • Start_Date
  • End_Date
  • Reward_Amount

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!

3
  • what is DCRA in the foreach? seems like it should be item? Commented Nov 6, 2014 at 12:09
  • @IsThatSo You are correct I have only just realised that thanks alot! Commented Nov 6, 2014 at 12:10
  • Actually this has nothing to do with asp.net and grid view, but with ADO.NET. I have fixed the tags accordingly. Commented Nov 6, 2014 at 12:23

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for helping! I knew i had to allow it null somewhere. I tried adding AllowNulls to my GridView and it didnt work. Thanks for the answer.
Is there a way to say if its Null dont display anything in the datagrid for that cell?
Check this answer stackoverflow.com/questions/15218714/… for displaying null in DataGrid.
0

Please use this property to handle null values into grid.

Property : nulldisplaytext="xxx"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.