Binding to a DataGrid

G

Guest

I have a windows form with a DataGrid, and I want to bind a dataset to it. But I also have a combobox on my form, When the user chooses a number in the combobox, I want the datagrid bound to a query with the value from the combobox. Example, if the user chooses 2 in the combobox, I want the DataGrid to be bound to "SELECT * FROM schedule WHERE week = "2". I am new to programming using code instead of just dragging stuff on my form, so please help.
 
W

William Ryan eMVP

Tom Nowak said:
I have a windows form with a DataGrid, and I want to bind a dataset to it.
But I also have a combobox on my form, When the user chooses a number in
the combobox, I want the datagrid bound to a query with the value from the
combobox. Example, if the user chooses 2 in the combobox, I want the
DataGrid to be bound to "SELECT * FROM schedule WHERE week = "2". I am new
to programming using code instead of just dragging stuff on my form, so
please help.

Ok, create a dataView based on the table that you are currently binding the
grid to and bind the grid to it.

So if you currently have

dataGrid1.DataSource = myDataSet.Tables["MyTable"];
use this
DataView dv = myDataSet.Tables["MyTable"].DefaultView;
//Make sure the DataView is declared at the module level so that the whole
class can see it. so actually you'll want to do

DataView dv; //at the top and then after filling the datatable add this
line
dv = myDataSet.Tables["MyTable"].DefaultView;

now, on the selectedIndexChanged event of the combobox....
dv.RowFilter = "ColumnNameYouWantToFilterOn = '" +
comboBox1.SelectedValue.ToString() + "'";

Now this will set the RowFilter of the dataview whenever the index changes
and then the data will be filtered accordingly. You can also use a
DataRelation but that's a bit more complex - if you are interested though
let me know and I'll walk you through it.

HTH,

Bill
--

W.G. Ryan, eMVP

http://forums.devbuzz.com/
http://www.knowdotnet.com/williamryan.html
http://www.msmvps.com/WilliamRyan/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top