Search code examples
c#xmldatagridviewrowfilter

Data grid row filter return less than


when i run this to filter my xml file it returns all rows even those higher than the given amount.

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;

this is my 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>

how can i make it return only those with Dayvisited less than 20 to the data grid?. i thought using textbox for the value was confusing something so i changed it to just use 20 and it still does it and i dont know why.

how i add user input to the file

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;
}

Solution

  • The basic problem is that you read the value of DayVisited as a string. So a comparison of "100" < "20" turns out to be true in a string comparison. This leads to the row being included into the result.

    In order to compare the value correctly, you have to convert it to an integer before:

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

    However, as your XML file contains a row without data for DayVisited at the beginning, you have to prepare for invalid data. Thus you have to check the length of the string before to exclude the invalid row:

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

    If you want to include the empty row in the result, change the FALSE to TRUE.