Ryan
Ryan

Reputation: 239

Get value of datarow in c#

I have a question regarding DataRows. I have a DataTable which I then converted into a list of DataRow's. Now I want the string information stored in each DataRow. How can I do this? This is my code:

List<DataRow> list = dt.AsEnumerable().ToList();

Upvotes: 16

Views: 115449

Answers (8)

SendETHToThisAddress
SendETHToThisAddress

Reputation: 3744

In case you don't want to parse to a List first then loop through a List, you can loop through the columns in the DataTable by using a nested for loop and accessing the .Columns.Count property.

foreach (row in myDataTable.Rows){
    for (int i = 0; i < myDataTable.Columns.Count; i++){
        Console.WriteLine(row[i]);
    }
}

Upvotes: 0

Simple Sandman
Simple Sandman

Reputation: 900

An alternative method in getting a list of DataRow is to Select() the DataTable. It returns a DataRow[] that can easily be converted into a list.

Example of a 2 column DataTable:

DataTable dt = new DataTable();
// TODO: Insert data into DataTable

foreach (DataRow row in dt.Select())
{
    Console.WriteLine();
    Console.WriteLine(row[0].ToString());
    Console.WriteLine(row[1].ToString());
}

Upvotes: 1

Arthur P
Arthur P

Reputation: 1060

You will have to use a standard indexers on DataRow:

string someValue =
list[0]["SomeColumn"] as string;

Or, if you want to work with the array of data coming from a row,

ArrayList lst = new ArrayList(list[INDEX_OF_THE_ROW].Count);

foreach(object value in list[INDEX_OF_THE_ROW])
{
    lst.Add(value);
}

Upvotes: 2

CrazyDart
CrazyDart

Reputation: 3801

    List<DataRow> list = dt.AsEnumerable().ToList();
    var mystring = list[0]["ColumnName"].ToString();

Upvotes: 1

Threekill
Threekill

Reputation: 189

This should do the trick. string t = list[row]["column name"].ToString();

Upvotes: 2

devsh
devsh

Reputation: 21

You can retrieve it by column name or index. So if the string you are trying to retrieve is in first column you can do list[rowNum][0].ToString()

Upvotes: 0

Samantha Branham
Samantha Branham

Reputation: 7451

You could do this,

foreach(var row in list)
{
    var value = row["ColumnName"] as string;
}

or this to get all string values of "ColumnName" lazily.

var values = list.Select(row => row["ColumnName"] as string);

Why would you turn a DataTable into a list, though? Just wondering.

Upvotes: 15

BentOnCoding
BentOnCoding

Reputation: 28228

Just use an index to access each element. The following code would acccess the first element in the list.

list[0].MyString;

Upvotes: 7

Related Questions