Convert.IsDBNull causes exception in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RICALJE
    New Member
    • Aug 2008
    • 3

    Convert.IsDBNull causes exception in C#

    Hi All,

    Could you help me in my problem in working on a project that imports excel file to a datatable the validation is to catch all null values in the excel file because it will should not allow null values in the data table. Unfortunately my code dud not work. Please see my code below.
    [code=c#]
    for (int i = 0; i < columnNameInt.L ength -1; i++)
    {
    try
    {
    myDataTable.Col umns[columnNameIntEx portEx[i]].DefaultValue = 0;
    myDataTable.Col umns[columnNameIntEx portEx[i]].AllowDBNull = false;
    myDataTable.Col umns[columnNameIntEx portEx[i]].ColumnName = columnNameInt[i];
    }
    catch
    {
    MessageBox.Show (columnNameIntE xportEx[i]);
    for (int j = 0; j < myDataTable.Row s.Count; j++)
    {
    MessageBox.Show ( "" + j);
    if(Convert.IsDB Null(myDataTabl e.Rows[j][i]))
    {
    throw new Exception("Erro r found in row #[" + (j+1) + "]. Please check." );
    }
    }
    }
    }
    [/code]
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    What part did not work on it?

    EDIT: Do you know in your FOR loop you are skipping the last item?

    Comment

    • RICALJE
      New Member
      • Aug 2008
      • 3

      #3
      Hi. I think i know now the problem. the problem is

      it always by pass the if statement dont know why. its strange..
      if(myDataTable. Rows[j][i].Equals(System. DBNull.Value))

      for example in my excel file i have only 1 null value it will continue to load in my datatable in C#.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        Well you should be checking for "" or empty string if its coming from excel.
        Also, yuo should correct your FOR loop to include all the entries (you are never making it to the last entry with your current for loop logic)

        Comment

        • RICALJE
          New Member
          • Aug 2008
          • 3

          #5
          thnx plater. i got the logic now. found out that the data table is correct but the datagrid have to contain a validation. we can close this issue now.:D

          Comment

          Working...