Basically just set the RowFilter on the DataView being displayed in the
grid. If you didn't specify a DataView, then the grid will be using the
DefaultView of the table. Actually instead of scrolling to the correct
position, it only shows the rows that match the search criteria.
I saw a presentation showing how to do this at the St. Louis CSharp.NET user
group in July 2003. The presenter gave us a link to a great educational
project...
http://www.zrgwortz.com/datagrids.zip
(I am not the author of this code, nor am I responsible for hosting this
file. There were no viruses or malicious code at the download site last
time I downloaded it, but I can not be held responsible for the destination
of the link.)
You would want to look at 'frmFiltering2.cs" containing the following:
============================================================================
====
private void FrmFiltering2_Load(object sender, System.EventArgs e)
{
//Get data
global.fillDS(ds,"select * from Customers","Customers");
global.fillDS(ds,"select '*ALL*' Country union select distinct Country from
Customers order by Country","Countries");
//Use the DefaultView so we can access the prebuilt table style
dgCustomers.DataSource = ds.Tables["Customers"].DefaultView;
//Apply the prebuilt table style
DataGridTableStyle ts = new DataGridTableStyle();
ts.MappingName = "Customers";
dgCustomers.TableStyles.Add(ts);
//Setup filter combo box
cbCountry.DataSource = ds.Tables["Countries"];
cbCountry.DisplayMember = "Country";
cbCountry.ValueMember = "Country";
//Force filtering event to fire first time
cbCountry.SelectedIndex = 0;
cbCountry_SelectedIndexChanged(null, System.EventArgs.Empty);
}
private void setFilters()
{
string filter = "";
//build filter string
// Check for a country
if (cbCountry.SelectedIndex > 0)
filter += "Country = '" + cbCountry.SelectedValue + "'";
// Check for a name
if (tbName.Text.Length > 0)
{
if (filter.Length > 0)
filter += " and ";
filter += " CompanyName like '" + tbName.Text + "%'";
}
//set filter
ds.Tables["Customers"].DefaultView.RowFilter = filter;
}
private void cbCountry_SelectedIndexChanged(object sender, System.EventArgs
e)
{
setFilters();
}
private void tbName_KeyUp(object sender, System.Windows.Forms.KeyEventArgs
e)
{
setFilters();
}
============================================================================
====
The downloadable code shows alot of other great features of DataGrids. Each
"lesson" is contained it it's own form. I recomend you take a look.
Michael Lang, MCSD