Вопрос

I am doing an foreach on all columns on my DataTables row. I want to get data from a specific column but cant figure out how to do it. See code.

DataTable dt = mHandler.GetRegistrtationProgress(customer);
int column = 1;
foreach (DataColumn dc in dt.Columns)
{
    string hutt = dc.ToString();
    if (column == 11)
    {
        if (hutt.Equals("1"))
        {
            addSpecificPicture();   
        }
    }
    else
    {
        if (hutt.Equals("1"))
        {
            addPicture(column);
        }
    }
    column++;
}

When i run this code I only get name on column but there must be a good method to get value? Or not?

Это было полезно?

Решение

Not clear what you are trying to achieve, but if you want to retrieve the value of your only one row for every column then you have to use the dc.ColumnName property

DataTable dt = mHandler.GetRegistrtationProgress(customer);
foreach (DataColumn dc in dt.Columns)
{
     string hutt = dt.Rows[0][dc.ColumnName].ToString();
     ....

Of course you could simply loop over the column of the row using an indexer

DataRow row = dt.Rows[0];
for(int i = 0; i < dt.Columns.Count; i++)
{
     string hutt = row[i].ToString();

There is also the option of the property ItemArray in the DataRow object where every element of the array contains the corresponding value

DataRow row = dt.Rows[0];
for(int i = 0; i < row.ItemArray.Length; i++)
{
     string hutt = row.ItemArray[i].ToString();
     ....

Другие советы

You have to go through the rows first, then columns.

foreach (DataRow dr in dt.Rows) {
    foreach(DataColumn dc in dt.Columns) {
        string hutt = dr[dc].ToString()
    }
}

Or like Steve answered, if you have only 1 row.

You also can have a look here

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top