Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

.net - 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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...