从 C# 中的数据表中获取单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13816490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Cell Value from a DataTable in C#
提问by Abdur Rahim
Here is a DataTable dt, which has lots of data.
这是一个DataTable dt,它有很多数据。
I want to get the specific Cell Valuefrom the DataTable, say Cell[i,j]. Where,
i -> Rows and j -> Columns. I will iterate i,j's value with two forloops.
我想从数据表中获取特定的单元格值,比如Cell[i,j]。其中,i -> 行和 j -> 列。我将用两个迭代 i,j 的值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;
}
}
采纳答案by Tim Schmelter
The DataRowhas also an indexer:
该DataRow也有一个索引:
Object cellValue = dt.Rows[i][j];
But i would prefer the strongly typed Fieldextension 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");
回答by Chamila Chulatunga
You probably need to reference it from the Rowsrather than as a cell:
您可能需要从而Rows不是作为单元格引用它:
var cellValue = dt.Rows[i][j];
回答by Nikola Davidovic
You can iterate DataTablelike this:
你可以DataTable像这样迭代:
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 DataTablecell, you can cast the object to whatever you want.
根据DataTable单元格中数据的类型,您可以将对象转换为您想要的任何内容。
回答by Emre Inan
You can call the indexer directly on the datatable variable as well:
您也可以直接在数据表变量上调用索引器:
var cellValue = dt[i].ColumnName
回答by whatdoyouNeedFromMe
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.
如果我正确理解了您的问题,您想显示填充数据表的一个特定单元格吗?这是我用来在我的 DataGrid 中显示给定单元格的内容。
var s = dataGridView2.Rows[i].Cells[j].Value;
txt_Country.Text = s.ToString();
Hope this helps
希望这可以帮助
回答by Adrita Sharma
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);
}

