Will Tuttle
Will Tuttle

Reputation: 450

ASP.NET get cell from DataRow in a datatable?

I was wondering how I could access the cells in a dataTable? I thought I could do something like

  foreach (DataRow siteRow in sites.Rows)
        {
            String siteName = siteRow.Cells[1].Text;
        }

but that doesn't seem to work like it would with a gridview. What should I do?

Upvotes: 2

Views: 5676

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460038

Use the indexer:

foreach (DataRow siteRow in sites.Rows)
{
    String siteName = siteRow[1].ToString(); // second column
    // or via name:
    siteName = siteRow["SiteName"].ToString; // if column name is SiteName
    // or even better via Field method which is strongly typed 
    // and supports nullable types:
    siteName = siteRow.Field<string>(1); // works also via name
}

Upvotes: 6

Related Questions