Avatar of trstill
trstill
 asked on

c# get datatable row column value by column name

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
 
.NET ProgrammingC#

Avatar of undefined
Last Comment
trstill

8/22/2022 - Mon
jhshukla

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

Noticed typo. Second one should be:
string s = DT.Rows[0].Item["PricePerItem"];
SAMIR BHOGAYTA

Hi, try this code

string s

s = DataTable.Rows[0].ItemArray["PricePerItem"]
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
trstill

ASKER
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
jhshukla

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.
trstill

ASKER
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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
jhshukla

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
ASKER CERTIFIED SOLUTION
aswathi

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
trstill

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