DataTable - Select only find row where value is less than 10?
I'm having a really hard ti开发者_开发问答me trying to figure out what's going on with the Select method of DataTable. Here's the data that I got back in a DataTable, called VotePeriods
:
PeriodID
Description
11
Test 11
10
Test 10
9
Test 9
...
...
1
Test1
Here's the code to select the period based on PeriodID:
if (VotePeriods.Rows.Count > 0)
{
DataRow[] vp = VotePeriods.Select("PeriodID = " + voteperiod);
if (vp.Length > 0)
{
return vp[0];
}
}
For some reason, if voteperiod
is 9 or less, then I have the correct row selected. But if I pass in a 10
or 11
, I have no data back, even though in my DataTable, PeriodID 10
and 11
exists. Any suggestion?
Thanks.
Hope below will work. Keep in mind to add single quotation for values always when using the select method with DataTable.
if (VotePeriods.Rows.Count > 0)
{
DataRow[] vp = VotePeriods.Select("PeriodID = '" + voteperiod +"'");
if (vp.Length > 0)
{
return vp[0];
}
}
Have you tried using LINQ to select? I've had bad luck with a DataTable.Select before.
if(VotePeriods.Rows.Count > 0)
{
var vp = from x in VotePeriods.AsEnumerable()
where x["PeriodID"] == voteperiod
select x;
}
Make sure the data type of your PeriodID column is numeric, like int
:
VotePeriods.Columns.Add("PeriodID", typeof(int));
精彩评论