Adding bound combobox to datagridview

前端 未结 1 1546
青春惊慌失措
青春惊慌失措 2020-12-19 22:30

The scenario is almost the same as http://arsalantamiz.blogspot.com/2008/09/binding-datagridview-combobox-column.html. but I can\'t get it working on c#...

I have my

相关标签:
1条回答
  • 2020-12-19 23:02

    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.

    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.

    The key code looks something like this:

    // 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.

    0 讨论(0)
提交回复
热议问题