Abdur Rahim
Abdur Rahim

Reputation: 4021

Get Cell Value from a DataTable in C#

Here is a DataTable dt, which has lots of data.

I want to get the specific Cell Value from the DataTable, say Cell[i,j]. Where, i -> Rows and j -> Columns. I will iterate i,j's value with two forloops.

But I can't figure out how I can call a cell by its index.

Here's the code:

for (i = 0; i <= dt.Rows.Count - 1; i++)
{
    for (j = 0; j <= dt.Columns.Count - 1; j++)
    {
        var cell = dt.Rows[i][j];
        xlWorkSheet.Cells[i + 1, j + 1] = cell;
    }
}

Upvotes: 65

Views: 466937

Answers (6)

Adrita Sharma
Adrita Sharma

Reputation: 22213

To get cell column name as well as cell value :

List<JObject> dataList = new List<JObject>();

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    JObject eachRowObj = new JObject();

    for (int j = 0; j < dataTable.Columns.Count; j++)
    {
        string key = Convert.ToString(dataTable.Columns[j]);
        string value = Convert.ToString(dataTable.Rows[i].ItemArray[j]);

        eachRowObj.Add(key, value);

    }

    dataList.Add(eachRowObj);

}

Upvotes: 5

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
{
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
        {
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();
        }
}

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

Upvotes: 7

whatdoyouNeedFromMe
whatdoyouNeedFromMe

Reputation: 105

If I have understood your question correctly you want to display one particular cell of your populated datatable? This what I used to display the given cell in my DataGrid.

var s  = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();

Hope this helps

Upvotes: -2

Emre Inan
Emre Inan

Reputation: 21

You can call the indexer directly on the datatable variable as well:

var cellValue = dt[i].ColumnName

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460118

The DataRow has also an indexer:

Object cellValue = dt.Rows[i][j];

But i would prefer the strongly typed Field extension method which also supports nullable types:

int number = dt.Rows[i].Field<int>(j);

or even more readable and less error-prone with the name of the column:

double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");

Upvotes: 145

Chamila Chulatunga
Chamila Chulatunga

Reputation: 4914

You probably need to reference it from the Rowsrather than as a cell:

var cellValue = dt.Rows[i][j];

Upvotes: 14

Related Questions