Sunday, December 8, 2013

C# Searching Data form DataTable does not work as expected

An XML file was loaded to the datatable and performed a search for the member id as shown bellow. For a few it was returning records and for the few while the data exists it did not return the data.

string path = WebConfigurationManager.AppSettings.Get("xmlFilePath");
 if (path.Length > 0)
 {
    ds.ReadXml(path);
    if (ds.Tables.Count > 0)
    {
       DataRow[] result = ds.Tables[0].Select(
                     string.Format("member_id={0}", memberID));
       if (result.Length > 0)
       {
          lblCardNumber.Text = result[0]["card_no"].ToString();
          lblPointsBalance.Text = result[0]["closing_balance"].ToString();
       }
    }
 }

The reason being member_id column was a string column and if the change was as shown below it did return the data.

       DataRow[] result = ds.Tables[0].Select(
                     string.Format("member_id='{0}'", memberID));

I am yet to find the reason for this issue. The correct way to find the string value is to add (') before and after the value. 

No comments: