数据网格行过滤器返回小于

时间:2017-07-08 11:15:03

标签: c# xml datagridview rowfilter

当我运行它来过滤我的xml文件时,它返回所有行,即使是那些高于给定数量的行。

DataSet ds = new DataSet();



ds.ReadXml("Database.xml");

string filter = "";
filter = "Dayvisited <= '20'";

DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView2.DataSource = dv;
dataGridView2.Columns[4].Visible = false;

这是我的xml

<root>
  <place>
    <Name />
    <Location />
    <Info />
    <Dayvisited />
    <userdata />
  </place>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>100</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>base</Name>
    <Location>x868 z986</Location>
    <Info>stuff</Info>
    <Dayvisited>20</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
    <userdata>u</userdata>
  </place>
  <place>
    <Name>home</Name>
    <Location>x-280 z 277</Location>
    <Info>home and more stuff</Info>
    <Dayvisited>125</Dayvisited>
    <userdata>u</userdata>
  </place>
</root>

我怎样才能让它只返回那些Dayvisited小于20的数据网格?我认为使用文本框的价值令人困惑的东西,所以我把它改成只使用20,它仍然做到了,我不知道为什么。

我如何将用户输入添加到文件

try
{

DataRow dr = ds.Tables[0].NewRow();
dr["Name"] = Nametb.Text;
dr["Location"] = Locationtb.Text;
dr["Info"] = Infotb.Text;
dr["Dayvisited"] = dayvisitcb.Text;
dr["userdata"] = "u";
ds.Tables[0].Rows.Add(dr);
ds.WriteXml("Database.xml");

}
catch (Exception)
{
throw;
}

1 个答案:

答案 0 :(得分:1)

基本问题是您将DayVisited的值读为字符串。因此,"100" < "20"的比较在字符串比较中证明是正确的。这导致行被包含在结果中。

为了正确比较该值,您必须在之前将其转换为整数:

filter = "Convert(Dayvisited, System.Int32) <= 20"

但是,由于您的XML文件在开头包含没有DayVisited数据的行,因此您必须准备无效数据。因此,您必须先检查字符串的长度,然后排除无效的行:

filter = "IIF(LEN(DayVisited) = 0, FALSE, Convert(Dayvisited, System.Int32) <= 20)"

如果要在结果中包含空行,请将FALSE更改为TRUE