Tuesday, June 30, 2009

C#: Using comboBoxes in dataset/datatable bound dataGridViews

//Build fkey combobox 
 
var fKeyCombo = new DataGridViewComboBoxColumn
{
// most of these are frequently string values or constants 
HeaderText = "States", // The column header text 
DisplayMember = "StateAbbreviation",
// what field from the fkey table to display (list of names) 
Name = "state", // will be the name you use when you reference the column in the dataGridView 
ValueMember = "Id", // fkey link column typically the column in the foreign key table you join the main table on 
DataPropertyName = "stateId" // main table field you are replacing with a comboBox 
};
 
BindingSource fkey1Binding = new BindingSource();
var Fkey1Table = db.getDs().TechObjTypes;
 
fkey1Binding.DataSource = Fkey1Table; fKeyCombo.DataSource = fkey1Binding;
dataGridView1.Columns.Add(fKeyCombo);
 
//Add other fkey columns here or just delete below, and use the snippet over again  
//Sets up the main Table for dataGridView binding comment out or delete if using multiple fkey snippets //best declared with a larger scope than this function so it can later be submitted to the tableAdapter for updates
 
var mainTable = DataSet1.mainTable();
var MainBinding = new BindingSource();
MainBinding.DataSource = mainTable;
dataGridView1.DataSource = MainBinding;
//Must call MainBinding.EndEdit(); after updates, so it will update the MainTable 
// then you can pass the mainTable to a dataAdapter to do all the updates. 

No comments:

Post a Comment