tags:

views:

37

answers:

3

Hello,

I am still in the process of learning Asp.Net. I have a question . I was using an if condition in which i was checking dataset values. It is throwing me an exception whenever it is checking the condition as the dataset has not got any value. How to overcome this. Code for this is here:

DataSet ds = merchant.getIsactiveIsconfirmedforcancelaccount(merchantID);

if (_merchant.PackageID == (int)CommonHelper.Package.Free && _merchant.AccountStatus.Contains("Awaiting"))
        {
            spnMerchantActiveStatus.InnerHtml = ApplicationData.MSG_AWAITING_CONFIRMATION;
        }
        ***else if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" && (ds.Tables[0].Rows[0]["Active"]).ToString() == "N")***
        {
             _merchant.AccountStatus = "Cancelled";
             spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;

        }

        else if(_merchant.PackageID != (int)CommonHelper.Package.Free && ds1.Tables[0].Rows.Count == 0 && (ds2.Tables[0].Rows[0]["ConfirmationSrc"]).ToString() == "Admin")
        {
             _merchant.AccountStatus = "Free Trial";
             spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
        }
        else
            spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
    }

The exception here is "There is no row at position 0."

A: 

Seems like you do not have any rows in your tables[0]. You can add condition to check is rows > 0 and then continue with other conditions in the IF.

Sachin Shanbhag
A: 

You are assuming you have rows in your DataSet.

Instead of

if ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")

you should do something like

if ((ds.Tables[0].Rows.Count() > 0) &&
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" &&
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")

But you really need to do fuller error checking than just that one condition affectin you right now.

EDIT: If it's not obvious why the above works, read up on short-circuiting of logical operators: http://msdn.microsoft.com/en-us/library/2a723cdk(VS.71).aspx

gmagana
A: 

Try changing your else statement :

   else if (
(ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True" && 
(ds.Tables[0].Rows[0]["Active"]).ToString() == "N")  
    { 
    _merchant.AccountStatus = "Cancelled"; spnMerchantActiveStatus.InnerHtml = _merchant.AccountStatus;
    }

To

if ((null != ds.Tables[0]) && ((ds.Tables[0].Rows[0]["IsConfirmed"]).ToString() == "True") && ((ds.Tables[0].Rows[0]["Active"]).ToString() == "N"))

So that you check that the data set is not null before you check conditions on it.

or (as other posters say) check that you actually have rows in the dataset.

ds.Tables[0].Rows.Count() != 0
Dave
That won't work if there are no rows in the DataTable: ds.Tables[0].Rows[0] will cause a null reference exception.
gmagana
good point, probably best check the row count.
Dave