blah blah blah is here! blah blah » Close

up0down
link

I have a DataGridView that I am manually adding records from a remote XML File by using the below code. I am trying to add a filter that when the user types in the textbox it will only display the records which contain the text they type in. All the examples I have found show how to filter if your pulling from a data source, but since I am not pulling from a datasource how can I filter them?
Adding Records
dataGridTypes.Rows.Add(mnode["Name"].InnerText, mnode["Choices"].InnerText);
Trying to filter records
try
{
DataView dv = (DataView)this.dataGridTypes.DataSource;
dv.RowFilter = "Name like " + "'%" + txtType.Text.ToString() + "%'";
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}

last answered 2 years ago

1 answers

up0down
link

AFAIK, you can only build a DataView from a DataTable.
However, it's not difficult to build a DataTable manually. For example:
DataTable table;
private void Form1_Load(object sender, EventArgs e)
{
table = new DataTable();
DataColumn column;

column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "UserName";

table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Choices";

table.Columns.Add(column);
DataRow row;
row = table.NewRow();
row["UserName"] = mnode["Name"].InnerText;
row["Choices"] = mnode["Choices"].InnerText
table.Rows.Add(row);
// similar code for other rows to be added

dataGridTypes.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
DataView dv = new DataView(table);
dv.RowFilter = "UserName like " + "'%" + textBox1.Text + "%'";
dataGridView1.DataSource = dv;
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
Incidentally, I'd use something other than 'Name' for the first column (I've used 'Username' above) to avoid a strange error you otherwise get because of confusion with the form's Name property when the VS designer writes code to the InitializeComponent() method.

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback