Reputation: 1087
I have a datagridview with three columns which is filled using Datareader. There is a DatagridViewComboboxcolumn
in the datagridView.
I want this DatagridViewComboboxcolumn
should also be filled using datareader.
Please suggest how can i add items to DatagridViewComboboxcolumn using Datareader. Below is the code that i have tried.
Here dr is SqlDatareader
Datagridview.Rows.Add(dr("Column1").ToString, dr("Column2"),dr("DatagridViewComboboxcolumn "))
But when i add this way im getting error on the DatagridViewComboboxcolumn Column. Please Suggest
Upvotes: 4
Views: 7431
Reputation: 3970
As previously mentioned, you cannot set the DataSource of a DataGridViewColumn to a DataReader (since this is a forward only, database connected object). What you can however do is fill a DataTable and the set the DataSource on the DataGridViewColumn to this DataTable. You will also need to set the DataPropertyName (this is the column name of the DataGridView's datasource), ValueMemeber and DisplayMember. The example below uses the Adventureworks DB and populates a DataGridView with 4 columns (one of which is a combobox -- ProductIdCombo). Simply create a form, drop a DataGridGridView control on it named DataGridView1 and run the following. The ProductId column demonstrates that the underlying column bound to the combo (ProductIdCombo column)is indeed updating 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)
Upvotes: 3