c# get datatable row column value by column name

trstill
trstill used Ask the Experts™
on
Does anyone know how to get the value of a datatable row column using the column name.
I know using VB it is:
Dim var as string
 var = DT.Rows(0).Item("PricePerItem")

but I need the c# code to do the same thing.

Thanks
 
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
string s = DT.Rows[0]["PricePerItem"];
or
string s = DT.Rows[0].Items["PricePerItem"];

Commented:
Noticed typo. Second one should be:
string s = DT.Rows[0].Item["PricePerItem"];
Hi, try this code

string s

s = DataTable.Rows[0].ItemArray["PricePerItem"]
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Author

Commented:
ihshukla,
  Thanks for the answer and it does work.
I should have given more info.
This is what I'm actually trying to do by looping thru a datatable:
  DT is a Datatable
        foreach (DataRow row in DT.Rows)
        {
          String s row.item["PriceToItem"].ToString;
         }
But I get system.data.datarow does not contain a definition for item

Commented:
Can you place a breakpoint and check names of all columns in the datatable? There could be a few things wrong:
1. Typo when creating column names
2. Typo in code (PricePerItem vs PriceToItem)
2. Some columns were excluded in the query.

Author

Commented:
jhshukla,
  Thanks again for the reply.
I can do what you suggest but the column name is definitely correct.
The actual error is a compiler error that seems to be stating
the .item in row.item is not a valid definition or variable.

Hope this makes sense

Commented:
Oh, I thought it was runtime error. See the first way posted:
string s = DT.Rows[0]["PricePerItem"];

Open in new window

no need to .Item
Commented:
Please try this

          foreach (DataRow dr in DT.Rows)
            {
                string s = dr["PricePerItem"].ToString();
            }

Author

Commented:
Thanks aswathi,
  That's exactly what I need.
Seems so simple now that you showed me how to do it.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial