简体   繁体   中英

DataGridView comboboxcolumn dynamic binding

I'm building a pretty basic table editor for an SQL Server DB in C#; basically a bit like the old forms that used to come with MS Access for editing tables.

So far I have a combobox on the form where you select the table you want to edit, and then a datagridview that shows the table that has been selected in the combobox.

I want to add comboboxcolumns at runtime according to whether the column has a relationship or not , so the user can see the value they're picking, not just the ID.

So basically I don't know where the comboboxcolumns need to be (or what data they need to be bound to) until the user has selected a table. Hence this has to be done in code at runtime.

So far I'm populating the datagridview using:

String connectionString = sConnection;
dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource2.DataSource = table; 

So I'm guessing my route will be something like: populate the dgv, loop through the columns looking for anything with a relationship (how do I do that?!?), then change the type to comboboxcolumn, and then change the displaymember and valuemember properties for it to whatever they need to be (which I will need to get from somewhere...how???)

Can someone throw some code my way to point me in the right direction?

Thanks

it's possible: let's say you have the tables Employee and Department, you can find out that deptId in Employee table has a FK to Department.DeptId, fine, then you can get all columns of the Department table.

for how to find the FK you are interested in ( for the currently selected table ), google for it, for example I have found this: http://blog.sqlauthority.com/2007/09/04/sql-server-2005-find-tables-with-foreign-key-constraint-in-database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM