Reputation: 3143
I have a DataTable as follows:
OptionName OptionValue
'A' 100
'B' 85
'C' 75
'D' 60
I need to set a label 'lblMark'
with the Text in OptionName where the Option value is 85 for example.
EDIT:
What I'm currently doing is that i use a dropdownlist whose datasource is set to the DataTable above and i set the selected value to the value i want. This way i would get the name.
However i'm in a case where i do not want to display a dropdownlist
Upvotes: 1
Views: 91
Reputation: 148514
Using linq it's easy
lblMark.Text=dt.AsEnumerable().Where(dr=>Convert.ToInt32(dr["OptionValue"])==85).First()["OptionName "].ToString();
Notice that if there's no matches , you'll get an exception.
Safer code :
List<DataRow> lst =dt.AsEnumerable().Where(dr=>Convert.ToInt32(dr["id"])==5).ToList();
if(lst.Count==1)
{
lblMark.Text = lst[0]["OptionName"].ToString();
}
or
var lst =dt.AsEnumerable().Where(dr=>Convert.ToInt32(dr["id"])==5).SingleOrDefault();
if(lst!=null)
{
lblMark.Text = lst[0]["OptionName"].ToString();
}
I'm not sure how you sure about the availability of data , but if you get more than 1 , in FirstOrDefault , you'll have an exception.Oh well..
Upvotes: 1