且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将绑定组合框添加到 datagridview

更新时间:2023-10-14 14:09:40

最明显的错误是您对 datagridview 和组合框列使用相同的绑定源.如果您查看您提供的示例,您会注意到它们创建了第二个 bindingsource productBindingSource.

The most obvious thing that you are doing wrong is that you use the same binding source for both your datagridview and for your comboboxcolumn. If you look at the example you provided you'll notice that they create a second bindingsource productBindingSource.

因此,您需要做的是创建一个 bindingsource(我们称之为wizardProtocolBindingSource),然后用您的协议表中的数据填充它.这将成为组合框列的数据源.

So what you need to do is create a bindingsource (let's call it wizardProtocolBindingSource) which you then fill with the data from your protocols table. This becomes the datasource for your combobox column.

关键代码如下所示:

// You bind the datagridview just as before
// this dataset should have the idprotocols field which is your foreign key
// to the protocols table - you will probably want this to be hidden.
bindingSource = new BindingSource(); 
bindingSource.DataSource = dataSet; 
bindingSource.DataMember = "pcap"; 
dataGridView.DataSource = bindingSource; 

// hide the foreign key column
dataGridView.Columns["idProtocols"].Visible = false;

// here we populate your comboboxcolumn binding source
wizardProtocolBindingSource= new BindingSource(); 
// this dataset is from the protocols table
wizardProtocolBindingSource.DataSource = dataSet; 

// Add the combobox column
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();      
colType.HeaderText = "Type";      
colType.DropDownWidth = 90;      
colType.Width = 90;      
colType.DataSource = wizardProtocolBindingSource;      
// The DataPropertyName refers to the foreign key column on the datagridview datasource
colType.DataPropertyName = "wizardProtocol";    
// The display member is the name column in the column datasource  
colType.DisplayMember = "protocolName";    
// The value member is the primary key of the protols table  
colType.ValueMember = "idprotocols";    
// I usually just add the column but you can insert if you need a particular position  
dataGridView.Columns.Add(colType);      

以上应该对你有用,虽然不知道你的数据集列的名称我不得不猜测一下.

The above should work for you, though not knowing the names of your dataset columns I had to guess a little.