DataTable - 仅选择值小于10的查找行?

时间:2011-06-06 22:23:24

标签: c# .net select datatable row

我正在努力弄清楚DataTable的Select方法发生了什么。这是我在DataTable中获得的数据,称为VotePeriods

PeriodID Description

11 Test 11

10 Test 10

9 Test 9

...

...

1 Test1

以下是根据PeriodID选择期间的代码:

if (VotePeriods.Rows.Count > 0)
{
    DataRow[] vp = VotePeriods.Select("PeriodID = " + voteperiod);

    if (vp.Length > 0)
    {
        return vp[0];
    }
}

出于某种原因,如果voteperiod为9或更小,那么我选择了正确的行。但是如果我传入1011,我就没有数据,即使在我的DataTable中,PeriodID 1011也存在。有什么建议吗?

感谢。

3 个答案:

答案 0 :(得分:2)

希望下面会奏效。请记住,在使用带有DataTable的select方法时,请始终为值添加单引号。

if (VotePeriods.Rows.Count > 0)
{
    DataRow[] vp = VotePeriods.Select("PeriodID = '" + voteperiod +"'");

    if (vp.Length > 0)
    {
        return vp[0];
    }
}

答案 1 :(得分:0)

您是否尝试过使用LINQ进行选择?我之前使用DataTable.Select运气不好。

if(VotePeriods.Rows.Count > 0)
{

      var vp = from x in VotePeriods.AsEnumerable()
               where x["PeriodID"] == voteperiod
               select x;

}

答案 2 :(得分:0)

确保PeriodID列的数据类型为数字,例如int

VotePeriods.Columns.Add("PeriodID", typeof(int));
相关问题