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;
6/1/2018 7:41:48 AM

Accepted Answer

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");
4/24/2013 7:14:57 AM

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

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

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.


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);




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

var cellValue = dt[i].ColumnName

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