Reputation: 428
I have a DataGridView
which is bound to a datasource. I have also a TextBox
to filter the records. In TextChanged
event of the textbox I have a this line of code: i bind the gridview through designview of the form drag the gridview and choose datasource ... and then the member table.
(gvSideMember.DataSource as DataTable).DefaultView.RowFilter =
string.Format("F_NAME LIKE '%{0}%'", textSearch.Text);
But when I try to filter records it shows me that object reference is not set to an instance. The datasource has records. I don't know what's going on, kindly guide me, help will be appreciated.
Upvotes: 0
Views: 1562
Reputation: 171
You are using the as
keyword. Could it be that gvSideMember.DataSource
, although having records, is not of the type DataTable, so that (gvSideMember.DataSource as DataTable)
is null
?
Upvotes: 1
Reputation: 33139
If DataSource
is not a DataTable
, then (DataSource as DataTable)
returns null
.
What you can do, for instance, is this:
var src = gvSideMember.DataSource;
Put a breakpoint AFTER that line, then when you hit it, QuickWatch src
in Visual Studio to see its type and contents.
Then you can update your source code to use the proper type of DataSource
.
EDIT If the DataSource is a DataSet, it will contain one or more tables. If it contains a single table, that is easy to retrieve:
var src = (DataSet) gvSideMember.DataSource;
var table = src.Tables[0];
But if it contains more tables, you can retrieve it with the right number (0, 1, ...) or the name:
var table = src.Tables["MyTable"];
Upvotes: 1
Reputation: 250842
You can test nullity before the statement - in the example below I'm just logging that they are null, so you'll still get the error, but you can use these checks to either decide not to perform the operation or supply defaults etc.
if (gvSideMember == null) {
Debug.WriteLine("gvSideMember is null");
}
if (textSearch == null) {
Debug.WriteLine("textSearch is null");
}
(gvSideMember.DataSource as DataTable).DefaultView.RowFilter =
string.Format("F_NAME LIKE '%{0}%'", textSearch.Text);
You can test anything that could possibly be null - even (gvSideMember.DataSource as DataTable).DefaultView
if you like.
Upvotes: 0