简体   繁体   English

如何设置已动态添加到datagridview的组合框的索引

[英]How to set the index of a combobox that was dynamically added to a datagridview

So here is a bit of backstory to try and put things into context 因此,这里有些背景知识试图将其放入上下文中

First off the format of the data: I have two databases that are structured like this 首先是数据格式:我有两个结构如下的数据库

DB1 this table contains the Field_Id , along with all of the properties of the field DB2 this table contains broader information along with references to DB1 Field_Id , that reference is used for getting the Field_Name DB1此表包含Field_Id以及字段的所有属性DB2此表包含更广泛的信息以及对DB1 Field_Id引用,该引用用于获取Field_Name

so simple sql query to better describe 如此简单的sql查询以更好地描述

Select Field_Name From DB1 Where Field_Id = (select Field_Id From DB2 where param = %)

this returns a list that gets bound to a DataGridViewComboBox inside of a datatable. 这将返回绑定到数据表内部的DataGridViewComboBox的列表。 Now up to this point everything goes great, the ComboBox get added the whole DataGridView gets filled the issue arises here 到目前为止,一切进展顺利, ComboBox被添加,整个DataGridView被填充,这里出现了问题

for (int i = 0; i <= dataGridView1.RowCount - 2; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = valuetosetindex;
            dataGridView1.Refresh();
        }

The thing is this doesnt set the value of the ComboBox inside of the 0th column, if I were to just set the columns to strings it works but the value set doesnt work. 事实是,这并没有设置第0列内部的ComboBox的值,如果我只是将列设置为字符串,它可以工作,但设置的值不起作用。

Im more than happy to add more code if needed. 我非常乐意在需要时添加更多代码。

With your code snippet you are going to add an invalid value to the object which results in an ArgumentException . 使用代码段,您将向对象添加一个无效值,这将导致ArgumentException

Like you have already mentioned, if you assign a string to the value it is working. 就像您已经提到的那样,如果您将字符串分配给该值,那么它将起作用。 You only have to access the valuetosetindex element of the ComboBox : 您只需要访问ComboBoxvaluetosetindex元素:

dataGridView1.Rows[i].Cells[0].Value = yourColumn.Items[valuetosetindex];

In this code snippet yourColumn is your ComboBox which is bound to the column. 在此代码段中, yourColumn是绑定到列的ComboBox

How is your Datagridview bound to data? 您的Datagridview如何绑定到数据? I would suggest to use a Dataset and a BindingSource to tie it togehter. 我建议使用数据集和BindingSource将其绑定在一起。 If you bind it you can choose to use a ComboBox as a column type. 如果绑定它,则可以选择使用ComboBox作为列类型。 Then you can bind a second dataset to that Combobox. 然后,您可以将第二个数据集绑定到该组合框。 this would automatically create the link. 这将自动创建链接。

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

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