如何使用用户输入C#从XML文件中过滤数据

时间:2016-04-29 09:49:56

标签: c# xml

我正在制作程序,在XML文件数据上执行某些功能,然后在网格视图中向用户显示具有正确权限的行,在我的程序中,用户可以输入一些像工资一样的值,程序必须显示所有具有网格视图中的表中的这个工资量,但是我如何使用用户输入来过滤数据,因为" .RowFilter"只取得我之前决定的价值,例如"工资> 1000"

1 个答案:

答案 0 :(得分:0)

让我展示一个如何使用RowFilter的简单示例,接收来自用户的输入。

using System;
using System.Data;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            //InitializeComponent();
            this.Width = 400;

            dtPersons = new DataTable();
            dtPersons.Columns.Add("Name", typeof(string));
            dtPersons.Columns.Add("Age", typeof(int));

            // Should be read from file
            dtPersons.LoadDataRow(new object[] { "John", 30 }, false);
            dtPersons.LoadDataRow(new object[] { "Smit", 35 }, false);
            dtPersons.LoadDataRow(new object[] { "Jack", 25 }, false);
            dtPersons.LoadDataRow(new object[] { "Brad", 20 }, false);
            dtPersons.LoadDataRow(new object[] { "Paul", 40 }, false);

            var dgv = new DataGridView { Parent = this, Dock = DockStyle.Top };
            dgv.DataSource = dtPersons;

            tbFilterName = new TextBox { Parent = this, Top = dgv.Bottom + 30, Width = 150 };
            nudFilterAge = new NumericUpDown { Parent = this, Top = tbFilterName.Top, Left = tbFilterName.Right + 50 };

            var btnFilterName = new Button { Parent = this, Top = dgv.Bottom + 60, Text = "Apply filter by Name", AutoSize = true };
            var btnBothFilters = new Button { Parent = this, Top = dgv.Bottom + 60, Text = "Apply both filters", AutoSize = true, Left = btnFilterName.Right + 20 };
            var btnFilterAge = new Button { Parent = this, Top = dgv.Bottom + 60, Text = "Apply filter by Age", AutoSize = true, Left = btnBothFilters.Right + 20 };

            btnFilterName.Click += BtnFilterName_Click;
            btnBothFilters.Click += BtnBothFilters_Click;
            btnFilterAge.Click += BtnFilterAge_Click;
        }

        DataTable dtPersons;
        TextBox tbFilterName;
        NumericUpDown nudFilterAge;

        private void BtnFilterAge_Click(object sender, EventArgs e)
        {
            string filter = $"Age > '{nudFilterAge.Value}'";
            dtPersons.DefaultView.RowFilter = filter;
        }

        private void BtnBothFilters_Click(object sender, EventArgs e)
        {
            string filter = $"Name = '{tbFilterName.Text}' or Age > '{nudFilterAge.Value}'";
            dtPersons.DefaultView.RowFilter = filter;
        }

        private void BtnFilterName_Click(object sender, EventArgs e)
        {
            string filter = $"Name = '{tbFilterName.Text}'";
            dtPersons.DefaultView.RowFilter = filter;
        }
    }
}