开发者

how to use cellValueChanged event in datadrid view to use filter function?

开发者 https://www.devze.com 2023-02-03 19:27 出处:网络
I write a function to filter datagridview(dgv) void filterDataGridView(DataGridView dgv, string columnName, string filterValue)

I write a function to filter datagridview(dgv)

void filterDataGridView(DataGridView dgv, string columnName, string filterValue)
{
    foreach (DataGridViewRow row in dgv.Rows)
    {
        if (row.Cells[columnName].Value.ToString().Contains(filterValue))
        {
            row.Visible = true;
        }
        else row.Visible = false;
    }
}

I have 2 dgv with same column!

. one of them is for searching in the secend dgv.

I write this function for dgv1.

first dgv has one row to write string in each column secend dgv contains data for searching.

please help me how can i use firs dgv ?-->(in each cell of dgv1 开发者_开发问答i write a string ,in dgv2 it be filter) how can i do that ? how can i set properties og dgv1 and what event will be helpful and how can i use it

thanks :)


If your DataGridViews are bound to a BindingSource why don't you use the BindingSource.Filter property instead of implementing your own filtration?


If I understand you correctly you want to use your first DataGridView (having the same column as the second but one row only) to insert filter strings in it.

So what's wrong with a code like this (just an example):

this.dataGridView1.ReadOnly = false;
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;

var colA = this.dataGridView1.Columns.Add("Col A", "Column A");
var colB = this.dataGridView1.Columns.Add("Col B", "Column B");

var rowIdx = this.dataGridView1.Rows.Add("Hello", "World");
this.dataGridView1.Rows[rowIdx].ReadOnly = false;


this.dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);

Handling CellValueChanged event to trigger your filter:

void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    var editedCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    var newValue = editedCell.Value;

    // apply filter here...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消