CrBruno
CrBruno

Reputation: 1003

If data set has rows?

I have one more question

I have this foreach statement:

foreach (DataRow dr_art_custsuply in ds.Tables["CustomerSupplier"].Rows)
{
    //Podaci iz CustomerSupplier-a

    //Id dobavljača
    string cust_id;
    if (!dr_art_custsuply.Table.Columns.Contains("Id"))
        cust_id = "";
    else if (dr_art_custsuply["Id"].ToString().Length <= 0)
        cust_id = "";
    else
        cust_id = dr_art_custsuply["Id"].ToString();

    //Naziv dobavljača
    string name;
    if (!dr_art_custsuply.Table.Columns.Contains("Name"))
        name = "";
    else if (dr_art_custsuply["Name"].ToString().Length <= 0)
        name = "";
    else
        name = dr_art_custsuply["Name"].ToString();  

   //GLN
   string gln;
   if (!dr_art_custsuply.Table.Columns.Contains("GLN"))
        gln = "";
   else if (dr_art_custsuply["GLN"].ToString().Length <= 0)
        gln = "";
   else
        gln = dr_art_custsuply["GLN"].ToString();
}

What I want to do is to check if ds.Tables["CustomerSupplier"].Rows exists, if not skip this for each, is it's there go trough code, I tried this if

(!ds.Tables.Contains("CustomerSupplier"))
{
}

but I got an error, so help help, how to write it?

Thanks!

Upvotes: 0

Views: 1868

Answers (3)

Oded
Oded

Reputation: 498914

If there are no rows, you current code will already skip the body of the foreach.

foreach (DataRow dr_art_custsuply in ds.Tables["CustomerSupplier"].Rows)

That line will go to the end of the foreach and no code in the body will execute if there are no rows.

Update:

It wasn't entirely clear from your question, but it appears that you need to check if the table is actually in the dataset. Wrap the following if around the foreach to test for its existence:

if(ds.Tables["CustomerSupplier"] != null)

Upvotes: 5

logicnp
logicnp

Reputation: 5836

Simply add the following condition before your foreach:

if(ds.Tables["CustomerSupplier"].Rows.Count > 0)

Upvotes: 0

Habib
Habib

Reputation: 223207

just add this check before your loop (It will not go in foreach if there are no rows)

if(ds.Tables["CustomerSupplier"].Rows.Count > 0)

Upvotes: 2

Related Questions