Get cell value from DataTable in C #

Here is a DataTable dt in which there is a lot of data.

I want to get a specific Cell Value from a DataTable, say Cell [i, j] . Where, i β†’ Rows and j β†’ Columns. I will forloops over the value of i, j with two forloops .

But I can’t understand how I can call a cell my index.

Here is 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; } } 
+23
c # datatable
Dec 11
source share
6 answers

DataRow also has 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 column name:

 double otherNumber = dt.Rows[i].Field<double>("DoubleColumn"); 
+70
Dec 11 '12 at 8:45
source share

You probably need to reference it with Rows , not the cell:

 var cellValue = dt.Rows[i][j]; 
+6
Dec 11 '12 at 8:45
source share

You can iterate over a DataTable as follows:

 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 data in the DataTable you can drop the object to whatever you want.

+2
Dec 11
source share

You can also call the indexer directly on the datatable variable:

 var cellValue = dt[i].ColumnName 
0
Oct 05 '14 at 12:34
source share

you cannot, but, Alternatively, you can use the table with which you populated the dataGridView.

0
Feb 01 '17 at 13:14
source share

If I understand your question correctly, do you want to display one specific cell of your populated datatable? This is what I used to display this cell in my DataGrid.

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

Hope this helps

-one
Jun 01 '17 at 9:24 on
source share



All Articles