find and solve || findandsolve.com
Please wait.....

Welcome back.






Before Read Terms of use

Check DataSet is Null or Empty in ASP.NET C#

Check DataSet is Null or Empty in ASP.NET C#

Tryi to convert DataSet  value in viewmodel using JsonConvert.DeserializeObject.When try to convert dataset value in viewmodel the "There is no row at position 0." type of issue r has been occured becauses of DataSet is null.

Here is my code

     DataSet ds = new DataSet();
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     sda.Fill(ds);
     if (!string.IsNullOrWhiteSpace(ds.Tables[0].Rows[0].ItemArray[0].ToString()))
     {
       string classInfo = ds.Tables[0].Rows[0].ItemArray[0].ToString();
       if (!string.IsNullOrWhiteSpace(classInfo))
         {
            model = JsonConvert.DeserializeObject<LibrarbyInfoViewModel>(classInfo);
         }
     }
     con.Close();

Answer

Option 1.

Count your ds.table row like as 

if (ds.Tables[0].Rows.Count != 0){
//do something here
 }
else{
//do someting is when your dataset is null or empty
}

here is your full code

 DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
  sda.Fill(ds);
   if (ds.Tables[0].Rows.Count!= 0)
      {
      string classInfo = ds.Tables[0].Rows[0].ItemArray[0].ToString();
       if (!string.IsNullOrWhiteSpace(classInfo))
         {
           model = JsonConvert.DeserializeObject<LibrarbyInfoViewModel>(classInfo);
         }
    }
   con.Close();


Option 2.


public static class DataSetExtensionsExample
{
    public static bool CheckDataSet(this DataSet dataSet)
    {
        return dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0;
    } }

Usage

if (ds.CheckDataSet())
{    // data is null here--do something here
}
else{
      // here your database is null-do somthing in the null or empty case
}

Option 3.

You can use true or false (bool) and return true. For all tables in dataset like as:

bool IsEmpty(DataSet dataSet){
    foreach(DataTable table in dataSet.Tables)
    if (table.Rows.Count != 0) return false;
    return true;
}

Optioin 4.


DataSet ds=new DataSet();
int count = ds.Tables.Count;
//if count is zero then dataset is null else count is grater then zeor the data has in your ds
if(count ==0){
//do someting
}







Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response