I'm quite lost in this error I'm getting. I have a Combobox that I added to my dgv, I am able to fill my combo-box with the values I want yet I keep getting an exception when I make a selection change on the dgv itself. Every time I choose a value from the combo box and then perform a selection change on the dgv the error that is thrown is : DataGridViewComboBoxCell is not valid . After this error is thrown, the value in the combo box is set to nothing.
This is my first time posting and I've done alot of research for the past two days and I can't seem to get anywhere. If you guys would like me to post my code I will do so. Thanks.
Edit: added my code:
cmbItem = New cboItem(dr.Item("strFolderName"), dr.Item("strFolderPath"), dr.Item("strEntryID"))
Dim dtmTmp As Date = oItem.ReceivedTime
dgvEmails.Rows.Insert(intEmailPosition, {False, dtmTmp.ToString("dd-MMM-yyyy hh:mm tt"), GetRecipientEmail(oItem), oItem.subject.ToString, cmbItem, oItem.conversationid.ToString, oItem.entryid.ToString, strFoundBy, oItem.body})
DirectCast(dgvEmails.Rows(intEmailPosition).Cells("cboFileTo"), DataGridViewComboBoxCell).Items.Add(cmbItem)
DirectCast(dgvEmails.Rows(intEmailPosition).Cells("cboFileTo"), DataGridViewComboBoxCell).DisplayMember = "DisplayText"
This is how I am adding the items into the combobox. Am I doing something wrong?
Edit: Added extra code
Dim cellComboBox As ComboBox = TryCast(e.Control, ComboBox)
RemoveHandler cellComboBox.SelectedIndexChanged, AddressOf Me.cellComboBox_SelectedIndexChanged
AddHandler cellComboBox.SelectedIndexChanged, AddressOf Me.cellComboBox_SelectedIndexChanged 'trapping the event handler
If cellComboBox IsNot Nothing Then
'load all values into the combox box
cellComboBox.MaxDropDownItems = 6 'drop down list can only have 5 items in there
Try
strEmail = dgvEmails.SelectedRows(0).Cells(2).Value.ToString 'cells(2) holds the email address
strConvoID = dgvEmails.SelectedRows(0).Cells(5).Value.ToString 'cells(5) holds the conversation id of the email
Catch ex As Exception
End Try
'call GetSuggestion function here
objclsSuggesstion.GetSuggestion(strConvoID, strEmail, NUMBER_SUGGESTIONS)
For intI = 0 To NUMBER_SUGGESTIONS - 1
dr = objclsSuggesstion.GetItem(intI)
If dr IsNot Nothing Then
'add dr to the combo box
cboItem = New cboItem(dr.Item("strFolderName"), dr.Item("strFolderPath"), dr.Item("strEntryID"))
'If Not cellComboBox.SelectedItem.FolderEntryID = cboItem.FolderEntryID Then 'if does not exist then add
cellComboBox.Items.Add(cboItem)
'End If
Else
Exit For
End If
Next
'cellComboBox.Items.Add(cboItem)
cboItem = Nothing 'make object nothing here
cboItem = New cboItem("", "", "", "<choose folder>...") 'create new object & add
'if <choose folder>... doesn't exist, then you add it.
Try
If Not cellComboBox.SelectedItem.DisplayText = cboItem.DisplayText Then
'cellComboBox.Items.Add(cboItem)
'DirectCast(dgvEmails.SelectedRows(0).Cells("cboFileTo"), DataGridViewComboBoxCell).Items.Add(cboItem)
'DirectCast(dgvEmails.SelectedRows(0).Cells("cboFileTo"), DataGridViewComboBoxCell).DisplayMember = "DisplayText"
cellComboBox.Items.Add(cboItem)
End If
Catch ex As Exception
End Try
I hope this helps?
I can't see all your code, but this is an example about adding a list of objects of type cmbItem to a DataGridViewComboBoxColumn
Public Class Form1
Dim myItems As New List(Of cmbItem)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
myItems.Add(New cmbItem() With {.Text = "yesterday", .DisplayText = Now.Date.AddDays(-1).ToString()})
myItems.Add(New cmbItem() With {.Text = "now", .DisplayText = Now.Date.ToString()})
myItems.Add(New cmbItem() With {.Text = "tomorrow", .DisplayText = Now.Date.AddDays(1).ToString()})
'find combobox in datagridview, passing column index
Dim ss = CType(DataGridView1.Columns(1), DataGridViewComboBoxColumn)
'add my items to combobox
For Each cmbItem As cmbItem In myItems
ss.Items.Add(cmbItem)
Next
'set combobox properties
ss.ValueMember = "Text"
ss.DisplayMember = "DisplayText"
End Sub
End Class
Public Class cmbItem
Property Text() As String
Property DisplayText() As String
End Class
Result:
If you want to add a new row, you must be sure to add a valid combobox value in the comboboxColumn. In the following code...
Private Sub AddRow()
DataGridView1.Rows.Add(New Object() {"New", myItems.First()})
DataGridView1.Rows.Add(New Object() {"New", "12/01/1984"})
End Sub
The first row is added correctly, the second one gives and exception like yours "DataGridViewComboBoxCell value is not valid."
There are a lot of ways to add new rows getting a valid combobox item, here are some examples
Private Sub AddRow2()
Dim ss = CType(DataGridView1.Columns(1), DataGridViewComboBoxColumn)
'adding from my list
DataGridView1.Rows.Add(New Object() {"New", myItems.First()})
'adding from current combobox Items
DataGridView1.Rows.Add(New Object() {"New", ss.Items.OfType(Of cmbItem).Last()})
'querying from combobox added items
Dim queryItem = (From i In ss.Items.OfType(Of cmbItem)() _
Where i.Text = "now" _
Select i).Single()
DataGridView1.Rows.Add(New Object() {"New", queryItem})
End Sub
Result
Related
I have a gridView control with a checkBox TemplateField. I am trying to delete records from the gridvie based on the checked checkbox control but keep getting the error
BC30456: 'Checked' is not a member of 'checkbox'.
below is my button_click subroutine which should do the delete.
Protected Sub DeleteSelectedProducts_Click(sender As Object, e As EventArgs) Handles DeleteSelectedProducts.Click
Try
Dim atLeastOneRowDeleted As Boolean = False
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = row.FindControl("ProductSelector")
If cb IsNot Nothing AndAlso cb.Checked Then
atLeastOneRowDeleted = True
Dim productID As Integer = _
Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
DeleteResults.Text &= String.Format( _
"This would have deleted ProductID {0}<br />", productID)
End If
Next
DeleteResults.Visible = atLeastOneRowDeleted
Catch ex As Exception
End Try
End Sub
I'm guessing this is WPF since both the WinForms CheckBox and the ASP.NET CheckBox have a Checked property.
For WPF you gotta use CheckBox.IsChecked:
If cb IsNot Nothing AndAlso cb.IsChecked Then
I have been tasked with creating a cinema booking system in VB.net by my teacher. So far I have created 50 CheckBoxes and I am trying to rename them all to seat (number). I have this code in my Form1.load but it is not working because it is a type and not an expression. I tried using a variable for this but it did not work.
Here is my code:
For count As Integer = 1 To 54 Step 1
CheckBox(count).text = "Seat " & count
Next
Please help, and or recommend me another way to accomplish this.
set the name of the checkbox when you create it. To find out how to create a checkbox programmatically add a checkbox to a form then look at .designer.vb
dim cb as new checkbox
cb.name = "1"
cb.text = "Seat 1"
you need to also add the location and other properties
If you have already created your textboxes with names like 1, 2 then iterate through and get the numbers like this: If you call them CB_1 then cut the CB_ off before looking for the number.
dim cbNumber as int16
For Each c As Control In myContainer.Controls
If c.GetType() Is GetType(CheckBox) Then
cbnumber = cint(c.name)
c.text = "Seat" & cbnumber
End If
Next
Well, here's my approach. In order to test just drop on a FlowLayoutPanel, a Button, and a NumericUpDownonto the form.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For count As Integer = 1 To 54 Step 1
' Make a new CheckBox
Dim chkBox As New CheckBox()
' Setup the Checkbox
With chkBox
.Tag = count.ToString
.Name = CStr("seatCheckBox" & count.ToString)
.Text = String.Format("Seat {0}", count)
.ThreeState = False
.Checked = False
End With
' add an event listener for the checkbox checkstate changed event
AddHandler chkBox.CheckStateChanged, AddressOf Me.CheckBox_CheckStateChanged
' Add the checkbox to the control
Me.FlowLayoutPanel1.Controls.Add(chkBox)
' Keep the user from picking something that doesn't exist
Me.NumericUpDown1.Maximum = CDec(count)
Next
' Add and event listener for the find button click event
AddHandler Button1.Click, AddressOf Me.FindButton_Clicked
End Sub
' Find the checkbox in the form and return it
Private Function GetCheckBox(ByVal seatNumber As Integer) As CheckBox
Dim chkbox As CheckBox
' Try to find the Checkbox
Try
chkbox = TryCast(Me.Controls.Find(CStr("seatCheckBox" & seatNumber.ToString), True).First, CheckBox)
Catch ex As Exception
chkbox = Nothing
End Try
'Check if the trycast worked
If IsNothing(chkbox) Then
Throw New ArgumentOutOfRangeException("seatNumber", "The seat number to be searched for was not found")
Else
Return chkbox
End If
End Function
' Handle the Chekbox checkState event.
Private Sub CheckBox_CheckStateChanged(sender As Object, e As EventArgs)
' Convert to Checkbox
Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
' Simple result string
Dim resultstring As String = CStr("Seat Number {0} is now {1}.")
' Set the values
Select Case chkBox.Checked
Case True
resultstring = String.Format(resultstring, chkBox.Tag, "taken")
Case False
resultstring = String.Format(resultstring, chkBox.Tag, "available")
End Select
' Display it
MsgBox(resultstring)
End Sub
Private Sub FindButton_Clicked(sender As Object, e As EventArgs)
Try
' Get the checkbox and return it's name
MsgBox(GetCheckBox(CInt(Me.NumericUpDown1.Value)).Name.ToString)
Catch ex As Exception
' Display the error
MsgBox(ex.Message)
End Try
End Sub
End Class
I've got 2 forms. Form A has a listbox and a Combobox. Form B has a DataGridView. In my A, my combobox is meant to represent groups for a task. e.g. Inbox, Important etc. So whenever I select an item from the comobobox e.g. I select the "Inbox" Item the DataGridViewer will sort all the rows which contain "Inbox" in one of the columns. This all works fine. I can view the sorted data.
To Load my data into the DataGridView I use:
Dim ds As DataSet
Dim dataset1 As New DataSet("datasetTasks")
Dim table1 As New DataTable("tableTask")
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = CreateDataset()
frm_Tasks.DataGridView1.DataSource = ds.Tables("tableTask")
LoadFromXMLfile("C:\Users\Beta4K\Documents\Tasks.FILE")
For Each dr As DataRow In ds.Tables(0).Rows
ListBox1.Items.Add(dr("TaskName").ToString())
Next
End Sub
Private Sub LoadFromXMLfile(filename As String)
If System.IO.File.Exists(filename) Then
Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType)
Dim readStream As FileStream = New FileStream(filename, FileMode.Open)
ds = CType(xmlSerializer.Deserialize(readStream), DataSet)
readStream.Close()
frm_Tasks.DataGridView1.DataSource = ds.Tables("tableTask")
Else
MsgBox("file not found! add data and press save button first.", MsgBoxStyle.Exclamation, "")
End If
End Sub
Private Function CreateDataset() As DataSet
table1.Columns.Add("TaskID")
table1.Columns.Add("TaskName")
table1.Columns.Add("TaskMessage")
table1.Columns.Add("TaskDate")
table1.Columns.Add("TaskTime")
table1.Columns.Add("TaskGroup")
dataset1.Tables.Add(table1)
Return dataset1
End Function
Here's the code for my Combobox:
ListBox1.Items.Clear()
Dim dv As New DataView(ds.Tables("tableTask"))
dv.RowFilter = "TaskGroup = '" + ComboBox1.SelectedItem + "'"
frm_Tasks.DataGridView1.DataSource = dv.ToTable("tableTask")
For Each dr As DataRow In ds.Tables(0).Rows
ListBox1.Items.Add(dr("TaskName").ToString())
Next
What this is meant to do is that it clears the listbox, and then reloads the items into the listbox from reading all the data in the DataGridViewer. Since it's already sorted all it has to do is add the items but it doesn't. Instead it just adds all the items regardless of the filter.
Can someone help me.
You loop over the datatable while you need to loop over the dataview
For Each dr As DataRowView In dv
ListBox1.Items.Add(dr("TaskName").ToString())
Next
I have a DataGridView (called DataGridViewSecurity) in VB.net (Visual Studio 2010) which is bound to a DataTable (called DataTableSecurity) in a DataSet (called DataSetSecurity). I have added a nonbound column (called nSecurityComboBox) that I set based on an integer field (called nSecLevel) in the DataTable. After setting the combobox, it doesn't display anything in the combobox, but when you select the combobox, the 5 values in it's items collection show.
Here's the code I'm using to add a record to the DataTable and then to set the combobox:
Sub Foo()
.
.
.
DataSetSecurity.Tables(0).Rows.Add(New Object() {sName, sID, sSec})
ComboCell_Select(nRow, 3, DataGridViewSecurity, sSecRecs.nSecLevel)
MessageBox.Show("Value for the combo set at " + DataGridViewSecurity.Rows(nRow).Cells(3).Value.ToString)
.
.
.
End Sub
Private Sub ComboCell_Select(ByVal dgvRow As Integer, _
ByVal dgvCol As Integer, _
ByRef DGV As DataGridView,
ByRef nComboBoxRow As Int16)
Try
Dim CBox As DataGridViewComboBoxCell = CType(DGV.Rows(dgvRow).Cells(dgvCol), DataGridViewComboBoxCell)
Dim CCol As DataGridViewComboBoxColumn = CType(DGV.Columns(dgvCol), DataGridViewComboBoxColumn)
CBox.Value = CCol.Items(nComboBoxRow)
DGV.UpdateCellValue(dgvCol, dgvRow)
'MessageBox.Show("New value in the combo box = " + CBox.Value.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The messagebox.show in Foo shows the correct value for the combobox, but nothing is displayed.
Anyone see what I'm doing wrong?
Thanks.
-NCGrimbo
In the end, I found some C# code that I converted to VB.net to fix the issue. Here's the code:
Private Sub DataGridViewSecurity_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridViewSecurity.EditingControlShowing
Dim cellComboBox As ComboBox = TryCast(e.Control, ComboBox)
If cellComboBox IsNot Nothing Then
' make sure the handler doen't get registered twice
RemoveHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
AddHandler cellComboBox.SelectionChangeCommitted, AddressOf Me.CellComboBoxOnSelectionChangeCommitted
End If
End Sub
Private Sub CellComboBoxOnSelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)
Dim comboBox As DataGridViewComboBoxEditingControl = TryCast(sender, DataGridViewComboBoxEditingControl)
If sender Is Nothing Then
Return
End If
If comboBox.SelectedItem Is Nothing Then
Return
End If
If Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem Then
Return
End If
Me.DataGridViewSecurity.CurrentCell.Value = comboBox.SelectedItem
End Sub
If I understand the question right, all values are in the combobox just not being selected by default properly? I think I just had this problem a few days ago, here's what I have now.
'Create the combobox column
Dim comboBox As New DataGridViewComboBoxColumn()
'Add some stuff to the combobox
comboBox.Items.Add("FirstItem")
comboBox.Items.Add("SecondItem")
'Select the first item
comboBox.DefaultCellStyle.NullValue = comboBox.Items(0)
'Now add the whole combobox to the DataGridView
dgvItems.Columns.Add(comboBox)
Hope this helps!
I had a DataGridView, and already able to add DataGridViewComboBoxColumn to it. It read data from database StoredProcedure using custom ValueDescriptor class, this is the code for it:
Shared Sub fillComboBoxCellUsingSP(ByVal comboBox As DataGridViewComboBoxColumn, ByVal proc_name As String, ByVal param As Object(), ByVal firstitem As String)
Dim dt As New DataTable
Utils.executeSP(proc_name, param, dt)
If comboBox.DataSource IsNot Nothing Then
comboBox.DataSource = Nothing
End If
comboBox.Items.Clear()
Dim VDP_Array As New ArrayList
VDP_Array.Add(New ValueDescriptionPair(Nothing, firstitem))
For Each row As DataRow In dt.Rows
VDP_Array.Add(New ValueDescriptionPair(row(0), row(1)))
Next
With comboBox
.DisplayMember = "Description"
.ValueMember = "Value"
.DataSource = VDP_Array
End With
dt.Dispose()
End Sub
It can display the data alright, but I can't select it programmatically, using this method:
Shared Sub selectInComboDataGrid(ByVal comboBox As DataGridViewComboBoxCell, ByVal value As String)
For Each o As ValueDescriptionPair In comboBox.Items
If o.Value IsNot Nothing AndAlso o.Value.ToString.Equals(value) Then
comboBox.Value = o
Exit For
End If
Next
End Sub
Actually, the line that read comboBox.Value = o is okay. But still, the combo box cell didn't display the value. Just empty. And sometimes, DataError event raised.
Is there any clue for this?
Thank you so much in advance.
Has been try to solve this for almost two hours... :)
Try to set the value to the DataGridView and not to ComboBox. Here an example:
comboBox.DataGridView(comboBox.ColumnIndex, comboBox.RowIndex).Value = o