简体   繁体   中英

Datagrid filter on column that between two age range

I have a datagridview with a column of type string that display values for age ranges such as:

0-18
19-100
0-100

I also have a filter textbox that would need to filter on the age range

(dgv1.DataSource as DataTable).DefaultView.RowFilter = 
string.Format("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text);

The problem is that if the user enter a number like 18, the grid does not return row for 0-100

How can I get the datagrid to return both 0-18 and 0-100?

I do not think you will be able to do this using the “LIKE” comparator since the values you are looking for are “numeric”. To get the filter you are looking for, you will need a filter with “>=” and “<=” to see if the target age is in the range. It is unclear how the data is originally received, if the “age range” in each row is a string as shown, then I suggest a couple of different hacky ways. In addition, it is unclear what other columns would be in the grid.

One “hacky” approach, would be to make a method that returns a new DataTable with only the rows that fall into the given target range. To help in this endeavor, a second method that takes an int (target value we are looking for), and a DataRowView (The AgeRange we are comparing the “target” value to). This “AgeRange” will be in the rows first column. Here we simply take that string range (“0-18”) and the target value (“18”) to see if this target value IS in the range, then return true or false depending on the result. This can be done using the string.split method to split the “AgeRange” string and int.TryParse to convert the strings into numbers. Below is an example of this.

private bool TargetIsInRange(int target, DataRowView row) {
  if (row.Row.ItemArray[0] != null) {
    string cellValue = row.Row.ItemArray[0].ToString();
    string[] splitArray = cellValue.Split('-');
    int startValue;
    int endValue;
    if (!int.TryParse(splitArray[0], out startValue)) {
      return false;
    }
    if (!int.TryParse(splitArray[1], out endValue)) {
      return false;
    }
    if (target >= startValue && target <= endValue)
      return true;
   }
  return false;
}  

The method above should come in handy when looping through the grids rows to figure out which rows go into the new filter DataTable . Next, a method that does this looping through the grid and returns a filtered DataTable . For each row in the grid, we could call the above method and add the rows that return true .

private DataTable GetFilterTable() {
  DataTable filterTable = ((DataTable)dgv1.DataSource).Clone();
  dgv1.DataSource = gridTable;
  int targetValue = -1;
  if (int.TryParse(textBox1.Text, out targetValue)) {
    foreach (DataGridViewRow row in dgv1.Rows) {
      DataRowView dataRow = (DataRowView)row.DataBoundItem;
      if (dataRow != null) {
        if (TargetIsInRange(targetValue, dataRow)) {
          filterTable.Rows.Add(dataRow.Row.ItemArray[0]);
        }
      }
    }
  }
  return filterTable;
}

It is unclear where you are calling this filter, if you are filtering “strings” then as the user types the filter string in the text box the grid will filter with each character pressed by the user. This is nice with strings, however, in this case using “numbers”, I am guessing a button would be more appropriate. I guess this is something that you will have to decide. Putting all this together using a Button click event to signal when to filter the grid may look something like below

private DataTable gridTable;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  gridTable = GetTable();
  FillTable(gridTable);
  dgv1.DataSource = gridTable;
  textBox1.Text = "18";
}

private void FillTable(DataTable dt) {
  dt.Rows.Add("0-18");
  dt.Rows.Add("19-100");
  dt.Rows.Add("0-100");
  dt.Rows.Add("17-80");
  dt.Rows.Add("18-80");
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("AgeRange", typeof(string));
  return dt;
}

private void button1_Click(object sender, EventArgs e) {
  if (textBox1.Text == "") {
    dgv1.DataSource = gridTable;
    return;
  }
  dgv1.DataSource = GetFilterTable();
}

Hacky Approach 2

The first approach works; however, I am guessing if there is a LOT of data and a LOT of filtering, this may become a performance issue. Therefore, in this approach, extra steps are taken in the beginning to take advantage of the DataTable s RowFilter feature, as the posted code is doing. Obviously as stated previously, we will not use the “LIKE” comparator, instead the “<=” and “>=” operators are used.

In order to accomplish this, we MUST somehow turn the given string range “XX-XX” into two (2) int s. Then “add” these integers to the DataTable . Then it will be easy to filter the table using the RowFilter property and the less than and greater than operators. One problem is that it will require “extra” work on our part to set up the grid's columns properly or these extra two columns of data will also display.

This can be done in the “designer” or manually in code. Without going into too much detail, it is useful to bear in mind that IF you assign a DataTable as a data source to the grid AND you set the grids AutoGenerateColumns property to false … THEN only the grid columns with DataPropertyName names that “match” one of the DataTable column names… will display. In this case, we only want the AgeRange column with the “XX-XX” strings to display, the other two new columns can remain hidden from the user. Setting up the grid column manually may look something like below, however you can do this in the designer. NOTE: the designer does not display an AutoGenerateColumns property, you have to do this in your code.

private void AddGridColumn() {
  DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
  col.Name = "AgeRange";
  col.DataPropertyName = "AgeRange";
  col.HeaderText = "Age Range";
  dgv1.Columns.Add(col);
}

The important point is that the DataPropertyName MUST match the target column name in the DataTable , otherwise the column will not display.

Next is the construction of the new DataTable . This method is given the original DataTable . A new DataTable is created with three (3) columns, AgeRange-string (displayed), StartRange-int and EndRange-int. The start and end columns will not be displayed. Once this new table is constructed, a foreach loop is started through all the rows in the original table. The string digits from the original tables row are “parsed” into actual numbers and added to the new DataTable along with the original “range” string. This method could look something like below. A helper method is further below to help split the age range string and return a number.

private DataTable GetSplitTable(DataTable sourceTable) {
  DataTable dt = new DataTable();
  dt.Columns.Add("AgeRange", typeof(string));
  dt.Columns.Add("StartRange", typeof(int));
  dt.Columns.Add("EndRange", typeof(int));
  foreach (DataRow row in sourceTable.Rows) {
    int startValue = GetIntValue(row.ItemArray[0].ToString(), 0);
    int endValue = GetIntValue(row.ItemArray[0].ToString(), 1);
    dt.Rows.Add(row.ItemArray[0], startValue, endValue);
  }
  return dt;
}

private int GetIntValue(string rangeString, int index) {
  string[] splitArray = rangeString.Split('-');
  int value = 0;
  int.TryParse(splitArray[index], out value);
  return value;
}

Putting all this together may look like below. Note, the button click event checks to see if the text box is empty, and if it is, will remove the current filter if one is applied.

private DataTable gridTable;
private DataTable splitTable;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  gridTable = GetTable();
  FillTable(gridTable);
  splitTable = GetSplitTable(gridTable);
  AddGridColumn();
  dgv1.AutoGenerateColumns = false;
  dgv1.DataSource = splitTable;
  textBox1.Text = "18";
}

private void FillTable(DataTable dt) {
  dt.Rows.Add("0-18");
  dt.Rows.Add("19-100");
  dt.Rows.Add("0-100");
  dt.Rows.Add("17-80");
  dt.Rows.Add("15-75");
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("AgeRange", typeof(string));
  return dt;
}

private void AddGridColumn() {
  DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
  col.Name = "AgeRange";
  col.DataPropertyName = "AgeRange";
  col.HeaderText = "Age Range";
  dgv1.Columns.Add(col);
}

private void button1_Click(object sender, EventArgs e) {
  string filterString = "";
  DataView dv;
  if (textBox1.Text != "") {
    filterString = string.Format("StartRange <= {0} AND EndRange >= {0}", textBox1.Text);
  }
  dv = new DataView(splitTable);
  dv.RowFilter = filterString;
  dgv1.DataSource = dv;
}

This Code:

("AgeRange LIKE '%{0}' OR AgeRange LIKE '{0}%'", textBoxFilter.Text)

is a redundant with two AgeRange LIKE

If you want to search like textBoxFilter.Text you can try

("AgeRange LIKE '%{0}%'", textBoxFilter.Text)

Or

StringBuilder rowFilter = new StringBuilder();
rowFilter.Append("AgeRange  Like '%" + textBoxFilter.Text + "%'");
(dgv1.DataSource as DataTable).DefaultView.RowFilter = rowFilter.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM