Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datarow selection

Status
Not open for further replies.

ludmann

Programmer
Apr 14, 2004
49
GB
I am selecting data rows from a datatable. I want to print each attributes of the row, with the code below. It works fine.

for(int i=0; i < selected_row.ItemArray.Length; i++)
{
if(selected_row.ToString().Trim() == "")
{
}
else

{
str = str + selected_row.ToString() + "\r\n";
}

}

However, I do not want to print the attribute if it is selected_row["EmailAddress"] or if it is selected_row["LastName"]

How can I build my if statement, so as to not to print attributes in the EmailAddress and LastName column?

Can anyone help?

Thank you, Marika
 
Marika,
If you know the indexes of your columns, and you don't think they'll ever change, then you could simply setup your if statement so that the indexes that correspond to the unwanted columns are skipped. For example, if the column index of the "LastName" column is 1 and the column index of the "Email" column is 6, you could write something like this:
Code:
[COLOR=green]// sr = selected row[/color]
[COLOR=blue]for[/color]([COLOR=blue]int[/color] i=0; i < sr.ItemArray.Length; i++)
{
  [COLOR=green]// Skip the 2nd and 7th columns[/color]
  [COLOR=blue]if[/color] !(i == 1 || i == 6)
  {
    [COLOR=blue]if[/color] (sr[i].ToString().Trim() == "")
    {}
    [COLOR=blue]else[/color]
    {
       str = str + sr[i].ToString() + "\r\n";
    }
  }
}
The best way to do it, however, would be to use the ToString() function of the DataColumn class, which returns the name of the column in question. Thus, you would do the following:
Code:
[COLOR=green]// dt is the DataTable object that 
// contains the rows[/color]
[COLOR=blue]for[/color]([COLOR=blue]int[/color] i=0; i < sr.ItemArray.Length; i++)
{
  [COLOR=green]// Skip columns Email and LastName[/color]
  string col = dt.Columns[i].ToString();
  [COLOR=blue]if[/color] (!(col == "LastName") || col == "Email"))
  {
    [COLOR=blue]if[/color] (sr[i].ToString().Trim() == "")
    {}
    [COLOR=blue]else[/color]
    {
       str = str + sr[i].ToString() + "\r\n";
    }
  }
}
Hope this helps!

JC

Friends are angels who lift us to our feet when our wings have trouble remembering how to fly...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top