DataGridView comboboxcolumn dynamic binding

徘徊边缘 提交于 2019-12-25 08:27:13

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/4922624/datagridview-comboboxcolumn-dynamic-binding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!