How to check and replace null value in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lad1412
    New Member
    • May 2012
    • 2

    How to check and replace null value in C#

    Code:
    private DataTable getSomething1(String text){
        DataTable dtb = new DataTable();
        ...
        ...
        return dtb;
    }
    
    ...
    
    protected void buttonCheck_Click(object sender, ImageClickEventArgs e){
        List<DataTable> dtList = new List<DataTable>(){
            getSomething(item1.Text),
            getSomething2(item2.Text),
            getSomething3(item3.Text),
            ...                
        };
    }
    Anyone can guide me a way to check and replace null values in dtList with String message "NO DATA" or allow them in dtList.
    Because when I met a null value in this List,it show an error like "There is no row at position..."
    I used C# in Webform

    Thanks in advance.
  • firexfighterx
    New Member
    • May 2012
    • 14

    #2
    Can you show more code of more along the lines of what you want to accomplish? Then i will able to better come up with a solution.

    Comment

    • lad1412
      New Member
      • May 2012
      • 2

      #3
      I have already find out a way to solve this error. Thanks

      Code:
      private String ConvertNullToEmptyString(DataTable element)
          {
              if (element.Rows.Count > 0) //just add this condition here
              {
                  if (!DBNull.Value.Equals(element.Rows[0]["FullName"]))
                      return (string)element.Rows[0]["FullName"] + " ";
                  else
                      return String.Empty;
              }
              return "NO DATA";
          }
      
      protected void ....(){
           List<DataTable> strList = new List<DataTable>(){
             GetItem1(txtName.Text),   //
             GetItem2(txtName.Text),   //I set this datatable dont have any value           
           };
      
          txtBox1.Text = ConvertNullToEmptyString(strList[0]);
          txtBox2.Text = ConvertNullToEmptyString(strList[1]);
      }

      Comment

      Working...