codemanapt
codemanapt

Reputation: 33

How to check and replace null value in C#

Anyone can guide me a way to check and replace null values in strList 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..."

private DataTable getSomething1(String text){
    DataTable dtb = new DataTable();
    ...
    ...
    return dtb;
}

...

protected void buttonCheck_Click(object sender, ImageClickEventArgs e){
    List<DataTable> strList = new List<DataTable>(){
        getSomething(txtInput.Text),
        getSomething2(txtInput.Text),
        getSomething3(txtInput.Text),
        ...                
    };
}

I used C# in Webform. Plz, help me to fix this code or guide me a way to solve it. Thanks in advance.

@tech, @ riffnl: Finally I get all of your ideas and it really work now. Anw, thanks all pro here for advices. So, this is my solution ^^

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),   //private DataTable GetItem1(String t)
       GetItem2(txtName.Text),   //...           
     };

    txtGrD_D.Text = ConvertNullToEmptyString(strList[0]);
    txtGrM_D.Text = ConvertNullToEmptyString(strList[1]);
}

Upvotes: 2

Views: 39132

Answers (4)

riffnl
riffnl

Reputation: 3183

Since you're using a datatable I assume you're not talking about NULL (or nill), but DBNull.. Change your function ConvertNullToEmptyString like this:

private String ConvertNullToEmptyString(DataTable element){ 
  if (element.Rows[0]["Fullname"] == DBNull.Value || element.Rows[0]["Fullname"] == null) {
    return "NO DATA";
  } else {
    return element.Rows[0]["Fullname"].ToString();
  }
}

as requested: new sample;

// a list of datatables each containing 1 row, wasn't that the point of datatables
    // anyway -- I think you don't have any rows, so let's try this:
    private String ConvertNullToEmptyString(DataTable element)
    {
        if (element.Rows.Count == 0)
        {
            return "NO DATA";
        }
        if (element.Rows[0]["Fullname"] == DBNull.Value || element.Rows[0]["Fullname"] == null)
        {
            return "NO DATA";
        }
        else
        {
            return element.Rows[0]["Fullname"].ToString();
        }
    } 
    protected void Test()
    {
        List<DataTable> strList = new List<DataTable>(){ 
           GetItem("test1"),   //private DataTable GetItem1(String t) 
           GetItem("test2")   //...            
         };
        txtGrD_D.Text = ConvertNullToEmptyString(strList[0]);
    }

Upvotes: 1

tech
tech

Reputation: 276

If the error is "There is no row at position...", then I guess the probelm is not that a string is null, but it is, instead, that you are trying to access a row that does not exist in the datatable.

In particular, in the line :

String s = element.Rows[0]["FullName"].ToString();

You try to access the first row of the datatable. What if the datatable is empty ? You get an error! So you should check if the datatable contains rows with something like this:

if (element.Rows.Count >0)

Answer to you comment: yes we can. modify your:

foreach (DataTable element in strList)

into something like:

foreach (DataTable element in strList)     
    {          
    if (element.Rows.Count>0)
        {
        if(strList.Any(item => item == null))          
            {                
          ConvertNullToEmptyStringelement);                                                 
            }
        txtItem1.Text = mytext ;          
        .....
        }
    else
        {
        txtItem1.Text = "No Data";          
        }      
    } 

This is as far as I can go without modifying too much your program structure.

Upvotes: 0

Mitja Bonca
Mitja Bonca

Reputation: 4546

Try it this way by using String.IsNullOrEmpty. I double a cell in dataTable can be null.

        //creating an example table with one row (no data inisde):
        DataTable table = new DataTable();
        table.Columns.Add("FullName", typeof(string));
        table.Rows.Add("");
        string str = ConvertNullToEmptyString(table);

    //method to check for string:
    private String ConvertNullToEmptyString(DataTable element)
    {
        String s = element.Rows[0]["FullName"].ToString();
        return (string.IsNullOrEmpty(s) ? "NO DATA" : s);
    }

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102743

You can use C#'s null coalescing operator ??:

string s = null;
s = s ?? "NO DATA";
// s now equals "NO DATA";

Upvotes: 8

Related Questions