95

Can anyone help me how to access for example value of first cell in 4th column?

a b c d
1 2 3 5
g n m l

for example, how to access to value d, if that would be datatable?

Thanks.

el ninho
  • 4,183
  • 15
  • 56
  • 77

7 Answers7

144

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • 4
    @OP Just keep in mind that you'll often want to check first to ensure that there really are enough rows/columns when hard coding values like this. – Servy Jan 26 '12 at 18:11
  • 1
    see also http://stackoverflow.com/a/13816531/638977 It suggestes `int number = dt.Rows[i].Field(j);` – Behzad Ebrahimi Aug 16 '16 at 09:08
80
string abc= dt.Rows[0]["column name"].ToString();
Sander
  • 392
  • 2
  • 13
ashok luhach
  • 801
  • 6
  • 2
13

You can also try (first cell in 4th column):

dt.Rows[0][3]
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
FrenkyB
  • 6,625
  • 14
  • 67
  • 114
8
foreach(DataRow row in dt.Rows)
{
    string value = row[3].ToString();
}
gabsferreira
  • 3,089
  • 7
  • 37
  • 61
7

data d is in row 0 and column 3 for value d :

DataTable table;
String d = (String)table.Rows[0][3];
athena
  • 279
  • 3
  • 11
1
public V[] getV(DataTable dtCloned)
{

    V[] objV = new V[dtCloned.Rows.Count];
    MyClasses mc = new MyClasses();
    int i = 0;
    int intError = 0;
    foreach (DataRow dr in dtCloned.Rows)
    {
        try
        {
            V vs = new V();
            vs.R = int.Parse(mc.ReplaceChar(dr["r"].ToString()).Trim());
            vs.S = Int64.Parse(mc.ReplaceChar(dr["s"].ToString()).Trim());
            objV[i] = vs;
            i++;
        }
        catch (Exception ex)
        {
            //
            DataRow row = dtError.NewRow();
            row["r"] = dr["r"].ToString();
            row["s"] = dr["s"].ToString();
            dtError.Rows.Add(row);
            intError++;
        }
    }
    return vs;
}
Ata Hoseini
  • 117
  • 1
  • 4
0

Assuming that the values in "SomeColumnName" are unique / distinct and that the value you are looking for in "NameOfColumnWhereIsTheValueYouLookingFor" is "Double".

double SomeDoubleValue = (double)SomeDataTable.Select("SomeColumnName = ValueWhichDetermineTheRowLocation").First()["NameOfColumnWhereIsTheValueYouLookingFor"]
Pepik
  • 111
  • 1
  • 6