[英]How add filter to datagridview
I am trying to load a csv file to datagridview and now i want to add filtering to the datagridview 我正在尝试将csv文件加载到datagridview,现在我想向datagridview添加过滤
How to do? 怎么做? Here's how I read and load csv file 这是我读取和加载csv文件的方式
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.Title = "Open CSV Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "CSV";
openFileDialog1.Filter = "CSV files (*.csv)|*.csv|All files(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
try
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string csvPath = openFileDialog1.FileName;
string rowValue;
// int rowValue = int.Parse(??);
string[] cellValue;
dataGridView1.Rows.Clear();
//dataGridView1.Columns.Clear();
if (System.IO.File.Exists(csvPath))
{
System.IO.StreamReader fileReader = new StreamReader(csvPath);
rowValue = fileReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i <= cellValue.Count() - 1; i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i]; //column name , value
column.HeaderText = cellValue[i];
dataGridView1.Columns.Add(column);
// dataGridView1.Columns[].CellType = typeof(Int64);
//Conver.ToString
dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; // Korean? 칼럼 헤더 가운데 정렬
// dataGridView1.RowHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
// dataGridView1.Columns[0].DataPropertyName = "field name";
}
while (fileReader.Peek() != -1)
{
rowValue = fileReader.ReadLine();
cellValue = rowValue.Split(',');
dataGridView1.Rows.Add(cellValue);
}
fileReader.Dispose();
fileReader.Close();`
Instead of adding rows directly to DataGridView
add them to a DataTable
and then set that table as DataSource
of your DataGridView
, then use that table.DefaultView.RowFilter
to filter the DataGridView
. 不是直接向DataGridView
添加行,而是将它们添加到DataTable
,然后将该表设置为DataGridView
DataSource
,然后使用该table.DefaultView.RowFilter
过滤DataGridView
。
You can simply change your code using below examples. 您只需使用以下示例更改代码即可。
Create a DataTable: 创建一个DataTable:
var table = new DataTable();
Add Column to DataTable: 将列添加到DataTable:
table.Columns.Add("column name");
Add Row to DataTable: 向DataTable添加行:
To add a row using a range for example a string[]
: 要使用范围添加行,例如string[]
:
table.Rows.Add(range);
Set the table as DataSource
of the DataGridview
将表设置为DataGridview
DataSource
dataGridView1.DataSource = table;
Filter using DataTable: 使用DataTable过滤:
To filter using the data table, for example to show only rows where FirstName
is John
: 要使用数据表进行过滤,例如仅显示FirstName
为John
行:
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "FirstName = 'John'";
Learn more: 学到更多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.