Need to populate a Dropdown combo box in Gridview, (unbound column) - vb.net

I'm having difficulty populating a dropdown list in my gridview.
I have created the column with the code below:
If Not Me.GridViewIsConstructed Then
gv.Columns.Add(createComboBoxWithDDL(Me.ddlGPField.Items, "Bank_GP_Field_Name", "GPField"))
gv.Columns.Add(createComboBoxWithDDL(Me.ddlBankField.Items, "Bank_Bank_Field_Name", "BankField"))
End IF
Private Function createComboBoxWithDDL(ByVal obj As Object, ByVal nDataFieldName As String, ByVal nColName As String) As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn
combo.DataSource = obj
combo.DataPropertyName = nDataFieldName
combo.Name = nColName
Return combo
End Function
The problem is that I cannot get the formatting handle to populate the combo box with the index that I need. here is my code attempts for the BankField DropDown List.
If e.ColumnIndex = gv.Columns("BankField").Index Then
e.FormattingApplied = True
Dim _row = gv.Rows(e.RowIndex)
Dim _cell As New DataGridViewComboBoxColumn
fillGPFieldList(_cell)
_cell.DisplayIndex = 1
_cell.DisplayMember = "Credit"
_cell.ValueMember = "Credit"
_cell.DataSource = _cell.Items
e.Value = _cell
End If
If e.ColumnIndex = gv.Columns("TrxType").Index Then
e.FormattingApplied = True
e.Value = "BAL"
End If
The Gridview displays the dropdown object just fine, its just always set to index -1.
Please help
V*********** Addendum Edit ***********V
Unfortunately, no one answered my question. So I worked around the entire problem. Its ugly and I would greatly appreciate any feedback.
I was never able to get the ComboBox to bind to the data source. I tried everything until I turned blue. So I went to the basics and coded all the automatic stuff. I'm curious as to why the automatic binding didn't work. Perhaps its because my gridview datasource was LINQ.
Here is how I pulled it off. I hope someone down the road benefits from the last 48 hours of my delima:
First of all, know that I have two drop down lists on my form, one is the GPField and the other is the BankField. These are already populated DDLs that are static. So I used them to cheat on the values instead of using enums.
I don't think it matters, but here is how I fill the GPField and BankField:
Sub fillGPFieldListDDL(ByVal obj As Object)
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the GP Field list
obj.Items.Clear()
For Each fld In db.getGPFieldList(Me.ddlImportID.SelectedItem, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
Sub fillBankFieldListDDL(ByVal obj As Object)
If String.IsNullOrEmpty(ddlImportID.Text) Then
Return
End If
Dim db As New CompanyDataDataContext
Dim myConn As New Connection With {.ConnCls = ConnCls}
myConn.dbConnect(db)
'Setup the Bank Field list
obj.Items.Clear()
For Each fld In db.getImportIDVirtualFields(Me.ddlImportID.Text, ddlImportTypes.BNKREC_IMPORTS_WORK)
obj.Items.Add(fld.Trim)
Next
db.Connection.Close()
db.Connection.Dispose()
db.Dispose()
End Sub
Next, based on a selection from the user, I populate my grid with the following function:
Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
ColumnNameData.Bank_Bank_Field_Number.ToString, _
FieldNames.BankField.ToString)
gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
gv.Rows.Clear()
Dim ri As Integer = 0
For Each r In _query3
Dim _row As New DataGridViewRow
_row.CreateCells(gv)
_row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
_row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
gv.Rows.Add(_row)
ri += 1
Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
So, the unanswered questions are:
1). I couldn't use the _query or _query2 as datasources for the gridview, but _query3 did work for simple textboxes.
2). If using _query3 as the gv.datasource, why would my combobox throw "bank_gp_field_name" not found error when the gv.Columns.Add(_comboCol) was executed
3). I understand the reason I couldn't do a gv bind to _query3 because of the data in Bank_Bank_field_number is an integer and the DDL values don't have a translation between the integer and the string value. But I commented out that field expecting the GPField to operate on a standard bind. I still got the "Field called "Bank_GP_Field_Name" does not exist on gv.Columns.Add(_comboCol)
So, summed up, why doesn't the code below work whereas the one above does?
Function fillToleranceFieldsGridView(ByVal nTrxType As String) As Integer
Dim myConn As New Connection With {.ConnCls = ConnCls}
Try
Using db As New CompanyDataDataContext
myConn.dbConnect(db)
'Dim _query As IEnumerable(Of TWO_Tolerance_Field) = (From tf In db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord) _
' Select tf)
'Dim _query2 As IEnumerable(Of TWO_Tolerance_Field) = db.getToleranceSetupRecordFields(nTrxType, BankToleranceRecordTypes.MasterRecord)
Dim _query3 = (From t In db.TWO_Tolerance_Fields _
Where t.TRXTYPESTRING = nTrxType And t.RCRDTYPE = BankToleranceRecordTypes.MasterRecord _
Select t.Bank_Bank_Field_Number, t.Bank_GP_Field_Name, t.TRXTYPESTRING)
Dim gv = Me.DataGridViewX1
gv.AutoGenerateColumns = False
gv.AllowUserToAddRows = False
gv.AllowUserToDeleteRows = False
gv.AllowUserToResizeRows = False
gv.AutoSize = True
gv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
gv.DataSource = _query3
If Not Me.GridViewIsConstructed Then
'Add in the combo box for GPField Names
Dim _comboCol As DataGridViewComboBoxColumn
_comboCol = CreateComboBoxColumn(Me.ddlGPField.Items, _
ColumnNameData.Bank_GP_Field_Name.ToString, _
FieldNames.GPField.ToString)
gv.Columns.Add(_comboCol)
'_comboCol = CreateComboBoxColumn(Me.ddlBankField.Items, _
' ColumnNameData.Bank_Bank_Field_Number.ToString, _
' FieldNames.BankField.ToString)
'gv.Columns.Add(_comboCol)
Dim col As DataGridViewColumn = _
New DataGridViewTextBoxColumn()
Dim _cell = New DataGridViewTextBoxCell
Dim _coll = New DataGridViewColumn(_cell)
Dim _colIndex As Integer = 0
''Bind to an existing column Left in for easy access for a simple text box
'_coll = New DataGridViewColumn(_cell)
'_coll.Name = ColumnNameData.Bank_GP_Field_Name.ToString
'_coll.ReadOnly = True
'_coll.HeaderText = ColumnNameData.Bank_GP_Field_Name.ToString
'_colIndex = gv.Columns.Add(_coll)
'gv.Columns(_colIndex).DataPropertyName = ColumnNameData.Bank_GP_Field_Name.ToString
Me.GridViewIsConstructed = True
End If
'gv.Rows.Clear()
'Dim ri As Integer = 0
'For Each r In _query3
' Dim _row As New DataGridViewRow
' _row.CreateCells(gv)
' _row.Cells(FieldNames.GPField).Value = r.Bank_GP_Field_Name.ToString.Trim
' _row.Cells(FieldNames.BankField).Value = ddlBankField.Items(r.Bank_Bank_Field_Number - 1).ToString.Trim
' gv.Rows.Add(_row)
' ri += 1
'Next
db.Connection.Close()
db.Connection.Dispose()
End Using
Return 0
Catch ex As Exception
Throw ex
Finally
myConn.Dispose()
End Try
End Function
Private Function CreateComboBoxColumn(ByVal obj As ComboBox.ObjectCollection, ByVal nDataFieldName As String, ByVal nColName As String) _
As DataGridViewComboBoxColumn
Dim column As New DataGridViewComboBoxColumn()
With (column)
.HeaderText = nColName
.DropDownWidth = 160
.Width = 90
.MaxDropDownItems = 3
.FlatStyle = FlatStyle.Flat
.DataSource = obj
.DataPropertyName = nDataFieldName
.Name = nColName
.ValueMember = nDataFieldName
.DisplayMember = .ValueMember
End With
Return column
End Function

Sorry if I've misunderstood or over simplified this but from what I gather the combox is binding fine you just cant set the index to 1? Is this because there is no underlying data for that cell?
Have you tried setting the default value of the column? From what I've read DataGridViewComboBoxColumn doesn't have a cell DefaultValue but works with column default.
Columns("ColumName").DefaultValue = 1
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.defaultvalue.aspx
You could also try handling DefaultValuesNeeded
Private Sub gv_DefaultValuesNeeded(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) _
Handles gv.DefaultValuesNeeded
With e.Row
.Cells("GPField") = 1
.Cells("BankField") = 1
End With
End Sub
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.defaultvaluesneeded(v=vs.110).aspx

Related

Can't display Data in ComboBox Control of DropDownStyle (DropDownList)

I have the following requirement,
I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database Table, and it's working fine.
(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.
(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.
Am I missing something here or is it like that? Any advice will be highly appreciated.
Im filling it in runtime using a procedure.
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
cmbDisProfile.DataSource = tempTb
cmbDisProfile.DisplayMember = "discount_profile"
End Sub
Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.
My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.
Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)
Return fetchedDataTable
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)
Dim SqlCmd As New SqlCommand(sqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
dataAdapter.Update(tbToUpdate)
End Sub
Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
Try
Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"
'Dim searchString As String = txtCategoryCode.Text
' searchOwnerCmd.Parameters.Clear()
' searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(searchSql)
If tempTb.Rows.Count = 0 Then
Return False
Else
Return True
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
Try
Dim SqlCmd As New SqlCommand(inputSqlString, conn)
Dim dataAdapter As New SqlDataAdapter(SqlCmd)
Dim fetchedDataSet As New DataSet
fetchedDataSet.Clear()
dataAdapter.Fill(fetchedDataSet)
Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)
Return fetchedSearchTB
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Function
OK. If I understood correctly, you have a problem in retrieving Data [String] from a Database Table into a ComboBox of DropDownStyle [DropDownList].
How do you fill/populate your ComboBox with Data From Database Table ?
In this link, Microsoft docs state, that:
Use the SelectedIndex property to programmatically determine the index
of the item selected by the user from the DropDownList control. The
index can then be used to retrieve the selected item from the Items
collection of the control.
In much more plain English
You can never SET ComboBox.Text Value while in DropDownList by code, which you already knew by testing your code, but you need to use DisplayMember and ValueMember or SelectedIndex.
ComboBox1.SelectedIndex = ComboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
Please consider populating your ComboBox Control from Database Table using (Key,Value) Dictionary collection, here is an example
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.
proposed,
ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"
does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),
Private Sub filldisProfiles()
Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
Dim i As Integer = 0
For i = 0 To tempTb.Rows.Count - 1
cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
Next
End Sub
After adding we can use the following code to display the data on combobox (DropDownList).
Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
Try
Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
Dim tempTb As DataTable
Dim myTbClass As myClassTableActivities = New myClassTableActivities()
tempTb = myTbClass.myFunctionFetchTbData(sqlString)
If Len(txtItCode.Text) < 4 Then
cmdAdd.Enabled = False
cmdDelete.Enabled = False
cmdSave.Enabled = False
Else
If tempTb.Rows.Count > 0 Then
With tempTb
txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
End With
cmdAdd.Enabled = False
cmdDelete.Enabled = True
cmdSave.Enabled = True
Else
cmdAdd.Enabled = True
cmdDelete.Enabled = False
cmdSave.Enabled = False
txtItName.Text = ""
Call fillItCategories()
Call fillProProfile()
Call filldisProfiles()
Call fillFinCat()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

DataGridView Yes No ComboBox Column

I have what on the face of it seems a pretty simple requirement, I need an unbound combobox column to hold an option list of 'Yes' and 'No'. In combobox parlance Yes and No are the DisplayMembers corresponding to ValueMembers 1 and 0 respectively which in turn are the values held in the field of the database table. I use bound combobox columns in the application extensively and am very familiar with building them, but can't for the hell of me work out how to incorporate this simple list functionality in the datagridview application. Could somebody please put me out of my misery with some sample code.
Thanks for your feedback Plutonix. The DGV is bound to an underlying table. Hopefully, the following code should give you some idea of what I am attempting to acheive. The code specifically relevant to this post is in the call to PopulateUnboundComboBox(comboBoxCol, {"Yes", "No"}).
Private Sub GetData()
Const procName As String = "GetData()"
Dim myValue As String = ""
Dim myDataSource As Integer = 0
Try
'First clear the existing grid
With Me.uxGrid
If .ColumnCount > 0 Then
'clear the grid
ClearGrid(Me.uxGrid)
End If
End With
_Logger.SendLog(Me.Name & "." & procName & " - Fetching device data.", NLog.LogLevel.Trace)
'Get the data from the database
If Not _dataSourceID = 0 Then
_sqlStatement = "SELECT ID, TEXT, CATEGORY, MOUNTING, DATASOURCEID, TANALYSIS" & _
" FROM P_TBL_DEVICE WHERE DATASOURCEID = " & _dataSourceID
_criteria = "WHERE DATASOURCEID = " & _dataSourceID
Else
_sqlStatement = ""
_criteria = ""
End If
_myDeviceMngr = New DeviceManager(_currentDB, _userName, _myPwd)
'Now get the latest data
_myDataSet = _myDeviceMngr.GetData(_sqlStatement)
_Logger.SendLog(Me.Name & "." & procName & " - Device data fetch completed.", NLog.LogLevel.Trace)
'Update the display
Call BuildGrid(_myDataSet, uxGrid)
Catch ex As Exception
Beep()
MsgBox(ex.Message, MsgBoxStyle.Exclamation, System.Windows.Forms.Application.ProductName)
_Logger.SendLog(ex.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, ex)
Finally
Call System.GC.Collect()
End Try
End Sub
Private Sub BuildGrid(ByVal myDataSet As DataSet, ByVal myGrid As DataGridView)
Dim myTable As New System.Data.DataTable
Dim myColCount As Integer
Dim comboBoxCol As DataGridViewComboBoxColumn
Dim readOnlyCellStyle As New DataGridViewCellStyle
Dim textBoxCol As DataGridViewTextBoxColumn
Dim gridObject As Object = Nothing
Const procName As String = "BuildGrid"
readOnlyCellStyle.ForeColor = Color.Gray
Try
_Logger.SendLog(Me.Name & "." & procName & " - Building device data grid.", NLog.LogLevel.Trace, Nothing)
myTable = myDataSet.Tables(0)
With myGrid
'Now add the columns to the grid
Dim column As System.Data.DataColumn
For Each column In myDataSet.Tables(0).Columns
'We dont want to include the changedon and changedby fields in the grid build
If column.ColumnName.IndexOf("CHANGED") = -1 Then
Select Case column.ColumnName
Case "DATASOURCEID"
gridObject = New Object
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
PopulateScadaSourceComboBoxCol(comboBoxCol)
comboBoxCol.DataPropertyName = "DATASOURCEID"
comboBoxCol.HeaderText = "SCADA SOURCE"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
Case "TEXT"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = column.ColumnName.Replace("TEXT", "DEVICE")
gridObject.name = column.ColumnName.Replace("TEXT", "DEVICE")
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "CATEGORY"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "CATEGORY"
gridObject.name = "CATEGORY"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "MOUNTING"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "MOUNTING"
gridObject.name = "MOUNTING"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "TANALYSIS"
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
PopulateUnboundComboBox(comboBoxCol, {"Yes", "No"})
comboBoxCol.DataPropertyName = "TANALYSIS"
comboBoxCol.HeaderText = "TELECONTROL ANALYSIS"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
Case Else
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "ID"
gridObject.name = "ID"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
End Select
'Now add the textbox columns to the grid
'gridObject.DataPropertyName = column.ColumnName.ToString
'gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
.Columns.Add(gridObject)
End If
Next
'Set grid default styles/values
.Font = New System.Drawing.Font("Arial", 10, FontStyle.Regular)
.AllowUserToResizeColumns = True
.AllowUserToResizeRows = True
.AllowUserToAddRows = True
.ReadOnly = True
.AutoResizeRows()
.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
'Now bind the datatable to the DGV datasource property
.DataSource = myTable
End With
_Logger.SendLog(Me.Name & "." & procName & " - Building of device data grid has been completed.", NLog.LogLevel.Trace, Nothing)
Catch ex As Exception
Throw
Finally
textBoxCol = Nothing
comboBoxCol = Nothing
readOnlyCellStyle = Nothing
GC.Collect()
End Try
End Sub
Private Sub PopulateUnboundComboBox(ByVal comboBoxCol As DataGridViewComboBoxColumn, byval valList() as string)
comboBoxCol.Name = "TANALYSIS"
comboBoxCol.DataSource = valList
comboBoxCol.ValueMember = ???
comboBoxCol.DisplayMember = ???
End Sub
EDITED//
Ok, I've made some progress and seem to have almost solved my issue. The one remaining bug is that the column in the DGV is displaying the 'ValueMember' (1 or 0) rather than the 'DisplayMember' (Yes or No). I've checked the valuemember and displaymember properties in the comboboxcolumn definition and and they appear to be set correctly. Here is the associated code:
Excerpt from original code posting listed above
...
Case "TANALYSIS"
gridObject = New Object
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
Dim item As New CBOItem
Dim itemList As New CBOItemList
item.ValueMember = 0
item.DisplayMember = "No"
itemList.Add(item)
item = New CBOItem
item.ValueMember = 1
item.DisplayMember = "Yes"
itemList.Add(item)
PopulateComboBox(comboBoxCol, itemList)
comboBoxCol.DataPropertyName = "TANALYSIS"
comboBoxCol.HeaderText = "TELECONTROL ANALYSIS"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
...
Private Sub PopulateComboBox(ByRef comboBoxCol As DataGridViewComboBoxColumn, ByVal itemList As CBOItemList)
Dim tbl As DataTable = New DataTable
Dim row As DataRow
tbl.Columns.Add("ValueMember")
tbl.Columns.Add("DisplayMember")
row = tbl.NewRow
row.Item("ValueMember") = itemList(0).ValueMember
row.Item("DisplayMember") = itemList(0).DisplayMember
tbl.Rows.Add(row)
row = tbl.NewRow
row.Item("ValueMember") = itemList(1).ValueMember
row.Item("DisplayMember") = itemList(1).DisplayMember
tbl.Rows.Add(row)
comboBoxCol.ValueMember = tbl.Columns("ValueMember").ToString
comboBoxCol.DisplayMember = tbl.Columns("DisplayMember").ToString
comboBoxCol.DataSource = tbl
End Sub
Kind Regards
Paul J.

Image.FromStream is not a member of System.Windows.Forms.DataGridViewImageColumn

So I use this code to display my data in a DataGridView:
Sub display_Infodata()
DGUSERS.Rows.Clear()
Dim sql As New MySqlDataAdapter("select * from tbl_info", con)
Dim ds As New DataSet
DGUSERS.AllowUserToAddRows = False
DGUSERS.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DGUSERS.RowTemplate.Height = 40
sql.Fill(ds, 0)
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim xx As Integer = DGUSERS.Rows.Add
Dim uid As String = ds.Tables(0).Rows(i).Item(0).ToString
Dim sqls As New MySqlDataAdapter("select * from tbl_other where userid='" & uid & "'", con)
Dim dss As New DataSet
sqls.Fill(dss, 0)
With DGUSERS.Rows(xx)
If dss.Tables(0).Rows.Count > 0 Then
.Cells(0).Value = uid
.Cells(1).Value = ds.Tables(0).Rows(i).Item(2).ToString
.Cells(2).Value = ds.Tables(0).Rows(i).Item(3).ToString
.Cells(3).Value = ds.Tables(0).Rows(i).Item(4).ToString
.Cells(4).Value = ds.Tables(0).Rows(i).Item(5).ToString
.Cells(5).Value = ds.Tables(0).Rows(i).Item(6).ToString
.Cells(6).Value = dss.Tables(0).Rows(0).Item(1).ToString
.Cells(7).Value = ds.Tables(0).Rows(0).Item(2).ToString
.Cells(8).Value = ds.Tables(0).Rows(0).Item(8).ToString
.Cells(9).Value = ds.Tables(0).Rows(0).Item("Image")
.Cells(10).Value = dss.Tables(0).Rows(0).Item(2).ToString
.Cells(11).Value = dss.Tables(0).Rows(0).Item(3).ToString
Else
End If
End With
Next
End Sub
It displays and works, but my problem is that when I try to display the data in the DataGridView of another form it shows the following error:
This is what I use:
Try
With View_Info
Dim index As Integer
Dim selectedRow As DataGridViewRow
selectedRow = DGUSERS.Rows(index)
.UserID.Text = DGUSERS.SelectedRows(0).Cells("UserID").Value
.UserType.Text = DGUSERS.SelectedRows(0).Cells("UserType").Value
.Fname.Text = DGUSERS.SelectedRows(0).Cells("Firstname").Value
.Mname.Text = DGUSERS.SelectedRows(0).Cells("Middlename").Value
.Lname.Text = DGUSERS.SelectedRows(0).Cells("Lastname").Value
.Contact.Text = DGUSERS.SelectedRows(0).Cells("Contact").Value
.Standing.Text = DGUSERS.SelectedRows(0).Cells("Standing").Value
.Guardian.Text = DGUSERS.SelectedRows(0).Cells("Guardian").Value
.ContactG.Text = DGUSERS.SelectedRows(0).Cells("GuardianContact").Value
.DPCreated.Text = DGUSERS.SelectedRows(0).Cells("DateCreated").Value
.DPValidity.Text = DGUSERS.SelectedRows(0).Cells("Validity").Value
Dim img As Byte()
img = DGUSERS.SelectedRows(0).Cells("Image").Value
Dim ms As New MemoryStream(img)
.UploadImage.Image = Image.FromStream(ms)
.Show()
.Focus()
End With
Catch ex As Exception
MsgBox(ex.Message & " Please select a corresponding records.", MsgBoxStyle.Exclamation)
End Try
Any help please?
It's hard to see the full picture, but the problem is most likely that you have created a DataGridViewImageColumn which you've chosen to call Image.
The compiler will always choose local variables, properties or classes over library/pre-imported namespace objects with the same name. Thus, your column by the name Image will be used rather than System.Drawing.Image because the former is "more local".
Try specifying the namespace as well and it should work:
.UploadImage.Image = System.Drawing.Image.FromStream(ms)
So what I did to solve this is by:
Dim pCell As New DataGridViewImageCell
pCell = Me.DGUSERS.Item("Picture", e.RowIndex)
.UploadImage.Image = byteArrayToImage(pCell.Value)
and using this function:
Private Function byteArrayToImage(ByVal byt As Byte()) As Image
Dim ms As New System.IO.MemoryStream()
Dim drwimg As Image = Nothing
Try
ms.Write(byt, 0, byt.Length)
drwimg = New Bitmap(ms)
Finally
ms.Close()
End Try
Return drwimg
End Function

DataGridView Multiple Row Selection Issue

I am trying to check for multiple selections in a DataGridView with a For... Next Loop, but even though I have selected multiple rows, the only row with the property Selected=True is the first row in the selection. Is there a way around this?
MultiSelect is true on the DataGridView.
My code is as follows:
For Each dr As DataGridViewRow In dgv.Rows
If dr.Selected = True Then
intSelectedRow = dr.Index
SetTime("KeyEntry", dgv.Name, intSelectedRow)
End If
Next
Thanks
Try this:
Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
For Each selectedItem As DataGridViewRow In selectedItems
'Add code to handle whatever you want for each row
Next
End Sub
Dim Message As String = String.Empty
Dim FNL As FinalRpt = New FinalRpt()
For Each ItemRow As DataGridViewRow In DGVItems.Rows
Dim ISSelected As Boolean = Convert.ToBoolean(ItemRow.Cells("MyChkBox").Value)
If ISSelected Then
Message &= Environment.NewLine
Message &= ItemRow.Cells("I_ID").Value.ToString()
Dim SelectedRow As Integer = DGVItems.Rows.GetRowCount(DataGridViewElementStates.Selected)
Dim RPTItemsDA As OleDbDataAdapter
Dim RPTItemsDS As DataSet
Dim I As Integer
For I = 0 To SelectedRow Step 1
RPTItemsDA = New OleDbDataAdapter("Select Distinct * From stkrpt Where I_ID = " & DGVItems.SelectedRows(I).Index.ToString() & "", DBConnect)
RPTItemsDS = New DataSet
RPTItemsDA.Fill(RPTItemsDS, "stkrpt")
FNL.DGVReport.DataSource = RPTItemsDS
FNL.DGVReport.DataMember = "stkrpt"
Next
FNL.MdiParent = MDIParent1
FNL.StartPosition = FormStartPosition.CenterScreen
FNL.WindowState = FormWindowState.Maximized
Me.Hide()
FNL.Show()
ISSelected = False
End If
Next
MessageBox.Show(Message)

loop data in datalist

How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
Protected Sub DataList2_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs) Handles DataList2.ItemDataBound
For Each li As DataListItem In DataList2.Items
Dim labelasd As Label = DirectCast(e.Item.FindControl("**Label8**"), Label)
Dim reviewid As Integer = labelasd.Text
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim connection As SqlConnection = New SqlConnection(connectionString)
connection.Open()
Dim sql As String = "Select Count(reviewYes) AS Expr1 From ProductReviewHelp Where ProductReviewID = " & reviewid & ""
Dim command As SqlCommand = New SqlCommand(sql, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim countofreview As Integer = 0
Dim reviewcountboolean As Boolean
If (reader.Read()) Then
If (IsDBNull(reader.GetValue(0)) = False) Then
countofreview = reader.GetValue(0)
End If
End If
If countofreview = 0 Then
reviewcountboolean = False
Else
reviewcountboolean = True
End If
If (reviewcountboolean = True) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "Hello"
ElseIf (reviewcountboolean = False) Then
Dim label1 As Label = DirectCast(e.Item.FindControl(**"Label7"**), Label)
label1.Text = "No"
End If
Next
End Sub
How do i loop through each data in the datalist? Because i am currently getting one value from "Label8" which causes my "Label7" to show "No" for all.
You are looping on your DataList2 items but, at every loop, you update the label7 with the logic of the current item, effectively removing the result of the previous loop. This means that, when you reach the last item, the Label7 will reflect the string "Hello" or "No" depending on the logic applied to the last item in your loop.
Apart from this logical error, you have also numerous errors in the code shown.
The connection is never closed.
You use string concatenation instead of parameters.
You use ExecuteReader when in this case an ExecuteScalar is better
suited.
You can iterate through then using a loop here is an example
Try
readFromDL1 = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
readFromQ = DirectCast(SqlDataSource7.Select(DataSourceSelectArguments.Empty), DataView)
Catch ex As Exception
End Try
'End
'datalist1
i = 0
_rowCount = DataList1.Items.Count
If _rowCount > 0 Then
_getCall = DataList1.Items.Item(i).FindControl("lnkEdit")
End If
For Each readr As DataRowView In readFromQ
findQNumber = readr(1).ToString()
For Each readfdlr1 As DataRowView In readFromDL1
findQNumber1 = readfdlr1(1).ToString
Try
indexofitems = DataList1.Items.Item(i1).ItemIndex
If findQNumber.ToString = findQNumber1.ToString Then
_getCall = DataList1.Items.Item(indexofitems).FindControl("lnkEdit")
_getCall.Text = "Called"
_getCall.Enabled = False
_getCall.ForeColor = Drawing.Color.Red
_getCall.BackColor = Drawing.Color.Yellow
End If
i1 = i1 + 1
Catch e As Exception
End Try
Next
i1 = 0
i = i + 1