简体   繁体   English

DataGridView comboboxcolumn动态绑定

[英]DataGridView comboboxcolumn dynamic binding

I'm building a pretty basic table editor for an SQL Server DB in C#; 我正在为C#中的SQL Server DB构建一个非常基本的表编辑器; basically a bit like the old forms that used to come with MS Access for editing tables. 基本上有点像MS Access用来编辑表格的旧表格。

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. 到目前为止,我在表单上有一个组合框,您可以在其中选择要编辑的表,然后是一个datagridview,显示已在组合框中选择的表。

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. 我想根据列是否有关系在运行时添加comboboxcolumns,以便用户可以看到他们选择的值,而不仅仅是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. 因此,基本上,在用户选择表之前,我不知道combobox列需要放置在哪里(或它们需要绑定到什么数据)。 Hence this has to be done in code at runtime. 因此,这必须在运行时用代码完成。

So far I'm populating the datagridview using: 到目前为止,我正在使用以下方法填充datagridview:

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???) 所以我想我的路线将是这样的:填充dgv,遍历各列以查找具有关系的任何内容(我该怎么做?!?),然后将类型更改为comboboxcolumn,然后更改displaymember和它的valuemember属性可以满足它们的需要(我将需要从某个地方获取它...如何?)

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. 这有可能:假设您有表Employee和Department,您可以发现Employee表中的deptId拥有一个到Department.DeptId的FK,很好,那么您可以获取Department表的所有列。

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 有关如何查找您感兴趣的FK(对于当前选定的表),对于Google,例如,我已经找到了它: http : //blog.sqlauthority.com/2007/09/04/sql-server-2005在数据库中找到带有外键约束的表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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