Click here to Skip to main content
15,905,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to tabs, I'm trying to write a code so that if the text in the textbox in tab 1 matches a word in the datagridview in tab 2, only show those rows, is it possible?


Here's the code I've written ...

C#
private void textBox2_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
            }
            else
            {
                (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox2.Text);
            }


But nothing appears in the datagridview box when I run the program and I get the error message off...

An unhandled exception of type 'System.NullReferenceException' occurred in Monitoring and management system.exe

What I have tried:

C#
private void textBox2_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
            }
            else
            {
                (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox2.Text);
            }
Posted
Updated 11-Feb-18 21:02pm
v3

1 solution

It looks like dataGridView1.DataSource is not of type DataTable.
If dataGridView1 is bound to a DataSet, DataTable or DataView the following code should work
var cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource, dataGridView1.DataMember];
var dataView = (DataView)cm.List;
dataView.RowFilter = string.Format("Name='{0}'", textBox2.Text);
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900