Erfani
Erfani

Reputation: 11

Error in DataGridView Filter

I fill My Datagridview by using Linq Query in C#. I want to filter this datagridview using a Textbox.

The code of Textbox changed event is:

DataTable dt = new DataTable();

dt = (DataTable)(dataGridViewX4.DataSource);

dt.DefaultView.RowFilter = string.Format("T_P = '{0}'", Txt_T_P_Se.Text);

dataGridViewX4.DataSource = dt;

After running the program, this error appears:

Invalid Cast Exception Was Unhandled. Any help in understanding this issue would be greatly appreciated.

my DataSource is :

var Query= (from p in QcGerdBaf.Taghes where p.QGI_Id_Fk == QGI_Id_Selected select new { p.T_P, p.T_Id });

dataGridViewX4.DataSource = Query.ToList();

Upvotes: 1

Views: 421

Answers (2)

user3218707
user3218707

Reputation: 11

Try like so, just edit info.

(dataGridViewX4.DataSource as DataTable).DefaultView.RowFilter = string.Format("ID = '{0}'", Txt_T_P_Se.Text);

erase your code, and this should work.

    //DataTable dt = new DataTable();

//dt = (DataTable)(dataGridViewX4.DataSource);

//dt.DefaultView.RowFilter = string.Format("T_P = '{0}'", Txt_T_P_Se.Text);

//dataGridViewX4.DataSource = dt;

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28423

Try Like this

int value;  
DataTable dt = new DataTable();  
dt = (DataTable)(dataGridViewX4.DataSource);   
dt.DefaultView.RowFilter = string.Format("T_P = {0}",int.TryParse(Txt_T_P_Se.Text, out value));   
dataGridViewX4.DataSource = dt;

Upvotes: 1

Related Questions