简体   繁体   中英

How to handle “Out Of Index” exceptions in my DataSet?

Please, help me. It's been like 3 days now I'm fighting against this thing, I'm getting completely crazy.

I got Out Of Index Exception in this code. The code is used every time I push a button (from a set of 4 buttons).

My problem is every time I try to see if the row is empty, I got an exception error on my if .

//I get my dataset from my WFC from this
data = client.GetEtapes(numTransformateur, IdEtape); 

//If my dataset is empty : this is were everything blows up
if (DBNull.Value.Equals(data.Tables[0].Rows[0]))
{
    LblDateDebutEtape.Text = "Date de début d'étape : ";
    LblDateFinEtape.Text = "Date de fin d'étape : ";

    LblDateDebutEtape.Text = LblDateDebutEtape.Text + " " + data.Tables[0].Rows[0][1].ToString();
    LblDateFinEtape.Text = LblDateFinEtape.Text + " " + data.Tables[0].Rows[0][2].ToString();

    LblDateDebutEtape.Visible = true;
    LblDateFinEtape.Visible = true;

    //I need to fetch another kind of data
    set = client.GetSousEtapesWithCommentary(data.Tables[0].Rows[0][0].ToString());

    //Same test as before
    if (DBNull.Value.Equals(set.Tables[0].Rows[0]))
    {
        Dtg_Fichiers.DataSource = data.Tables[0];
        Dtg_Fichiers.Columns[0].Visible = false;
        Dtg_Fichiers.Columns[Dtg_Fichiers.ColumnCount - 2].Visible = false;
    }
}

//In any case. Thoses does not affect the data I fetch at all.
this.GetButtonAllEnabled(button);
Dtg_Fichiers.ClearSelection();

I've tried so much stuff, my code is like a battlefield now.

Thanks for your help.

EDIT : I'm just dumb. All I have is to go with "data.Tables[0].Rows.Count != 0" in my if. Dunno why it didn't worked before. Programming logic I guess

Check for this condition in place of your if block

if(data.Tables.Count > 0 & data.Tables[0].Rows.Count > 0)
{ //your code
}

Let me know, if it solves your problem. Also share the exception.

Try to check first if this is null value, because if it is you will have not 0 index.

if(data.Tables != null && data.Tables.Count > 0 && data.Tables[0].Rows != null && data.Tables[0].Rows.Count > 0)
{

}

Or you can do it smaller but not checking counts.

if(data.Tables != null &&  data.Tables[0].Rows != null )
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM