How to add items to a DatagridViewComboboxColumn DatagridView at run time

I have a datagridview with three columns that are populated using Datareader. There is a DatagridViewComboboxcolumn in the datagridView.

I want this DatagridViewComboboxcolumn also be populated using datareader.

Please suggest how I can add items to a DatagridViewComboboxcolumn using Datareader. Below is the code I tried.

Here dr is SqlDatareader

 Datagridview.Rows.Add(dr("Column1").ToString, dr("Column2"),dr("DatagridViewComboboxcolumn ")) 

But when I add this method, I get an error in the DatagridViewComboboxcolumn column. Suggest

+4
source share
1 answer

As mentioned earlier, you cannot set the DataSource DataGridViewColumn to a DataReader (since this is an object associated only with the database). However, you can populate the DataTable and set the DataSource in the DataGridViewColumn to this DataTable. You also need to set DataPropertyName (this is the column name of the DataGridView data source), ValueMemeber, and DisplayMember. The example below uses DB Adventureworks and populates the DataGridView with four columns (one of which is combobox - ProductIdCombo). Just create a form, delete the DataGridGridView control named DataGridView1, and run the following. The ProductId column shows that the base column associated with the combo column (ProductIdCombo) actually updates the ProductId field in the dtProductsInventory DataTable.

  Dim dtProductInventory As New System.Data.DataTable Dim dtProducts As New System.Data.DataTable Using objSqlServer As New System.Data.SqlClient.SqlConnection("Server=LOCALHOST\SQLEXPRESS; Integrated Security=SSPI;Initial Catalog=AdventureWorks") objSqlServer.Open() Dim sqlCmd As New System.Data.SqlClient.SqlCommand("select * from production.ProductInventory", objSqlServer) dtProductInventory.Load(sqlCmd.ExecuteReader) sqlCmd.CommandText = "Select * from production.product" dtProducts.Load(sqlCmd.ExecuteReader) End Using DataGridView1.AutoGenerateColumns = False DataGridView1.DataSource = dtProductInventory Dim colProductIdCombo As New System.Windows.Forms.DataGridViewComboBoxColumn() colProductIdCombo.DataSource = dtProducts colProductIdCombo.DisplayMember = "Name" colProductIdCombo.ValueMember = "ProductId" colProductIdCombo.DataPropertyName = "ProductId" colProductIdCombo.HeaderText = "ProductIdCombo" DataGridView1.Columns.Add(colProductIdCombo) Dim colProductId As New System.Windows.Forms.DataGridViewTextBoxColumn() colProductId.DataPropertyName = "ProductId" colProductId.HeaderText = "ProductId" DataGridView1.Columns.Add(colProductId) Dim colShelf As New System.Windows.Forms.DataGridViewTextBoxColumn() colShelf.DataPropertyName = "Shelf" colShelf.HeaderText = "Shelf" DataGridView1.Columns.Add(colShelf) Dim colQuantity As New System.Windows.Forms.DataGridViewTextBoxColumn() colQuantity.DataPropertyName = "Quantity" colQuantity.HeaderText = "Quantity" DataGridView1.Columns.Add(colQuantity) 
+3
source

All Articles