Get Selected Item From Combobox - vb.net

I have a combobox with items from a DataTable, the ff executes when the form loads:
dbConnection = New SqlCeConnection("Data Source=Journal.sdf")
dbDataAdapter = New SqlCeDataAdapter("SELECT * FROM setting_unit", dbConnection)
dbDataAdapter.Fill(dbTable)
cbxSettingsUnit.DataSource = New BindingSource(dbTable, Nothing)
cbxSettingsUnit.DisplayMember = "name"
cbxSettingsUnit.ValueMember = "name"
The method when there is a changed in the combox box:
Private Sub cbxSettingsUnit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxSettingsUnit.SelectedIndexChanged
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
MessageBox.Show(tempString)
End Sub
there is an error at the line:
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
How do I get the selected item from the combox box?

Most of the .net "listing-controls" who have a DataSource property search for the implementation of the IListSource. So if you set a DataTable as datasource, you're actually setting the DataTable.DefaultView as the datasource.
Me.ComboBox1.DataSource = myDataTabele
Equals
Me.ComboBox1.DataSource = myDataTabele.DefaultView
So now you have a ComboBox packed with items of type DataRowView.
Dim selectedRowView As DataRowView = DirectCast(Me.ComboBox1.SelectedItem, DataRowView)
Dim selectedDisplayMemberValue As String = Me.ComboBox1.SelectedText
Dim selectValueMemberValue As Object = Me.ComboBox1.SelectedValue
And this is how you should do it:
Private Sub cbxSettingsUnit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxSettingsUnit.SelectedIndexChanged
Dim item As DataRowView = TryCast(Me.cbxSettingsUnit.SelectedItem, DataRowView)
If (Not item Is Nothing) Then
With item.Row
'You have now access to the row of your table.
Dim columnValue1 As String = .Item("MyColumnName1").ToString()
Dim columnValue2 As String = .Item("MyColumnName2").ToString()
End With
End If
End Sub
So why did you get an error? Yes, you are trying to cast a DataRowView to an Integer.
' |
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString

Try this:
Dim row_v As DataRowView = comboBox1.SelectedItem
Dim row As DataRow = row_v.Row
Dim itemName As String = row(0).ToString()

You have to use this
tempString = cbxSettingsUnit.Items(cbxSettingsUnit.SelectedIndex).ToString

try using below code
Try
DS = New DataSet
Tabel = "SELECT * FROM setting_unit"
Dim CB As New OleDb.OleDbDataAdapter(Tabel, dbConnection)
CB.Fill(DS, "setting_unit")
'
Me.cbxSettingsUnit.DataSource = Prf.Tables(0)
Me.cbxSettingsUnit.ValueMember = "name"
Me.cbxSettingsUnit.DisplayMember = "name"
Catch ex As Exception
End Try

try this:
combo.datasource = datatable
combo.displaymember = "abbreviation"
combo.valuemember = "abbreviation"
then getting the selected item use this:
on SelectionChangeCommitted event of combo box put this:
tmpString=combo.selectedvalue
msgBox(tmpString)

Related

Check the item in ToolStripMenuItem dynamically through Sub Function

I am new to .Net Visual Basic, I am currently self learning and trying to make some small application.
I need a help on Checking a sub menu item of ToolStripMenuItem
Complete concept is like:
I have a datagridview in which user will be able to rearrange the column or make a column visible or Hidded for this I have Sub / Function like below:
Public Sub Fun_Grid_Colomn_Visibility(ByVal GridName As DataGridView, ByRef ColName As String, ByVal MS_col As ToolStripMenuItem, ChkVal As Boolean)
If ChkVal = True Then
With GridName
.Columns("" & ColName & "").Visible = False
End With
MS_col.Checked = False
Exit Sub
End If
If ChkVal = False Then
GridName.Columns("" & ColName & "").Visible = True
MS_col.Checked = True
Exit Sub
End If
End Sub
On the form close I will be saving the user grid format as below (Got code from another Q/A Post) :
Public Sub WriteGrideViewSetting(ByVal dgv As DataGridView, ByVal FileName As String)
Dim settingwriter As XmlTextWriter = New XmlTextWriter("C:\Users\<username>\Desktop\temp\" & FileName & ".xml", Nothing)
settingwriter.WriteStartDocument()
settingwriter.WriteStartElement(dgv.Name)
Dim count As Integer = dgv.Columns.Count
For i As Integer = 0 To count - 1
settingwriter.WriteStartElement("column")
settingwriter.WriteStartElement("Name")
settingwriter.WriteString(dgv.Columns(i).Name)
settingwriter.WriteEndElement()
settingwriter.WriteStartElement("width")
settingwriter.WriteString(dgv.Columns(i).Width.ToString())
settingwriter.WriteEndElement()
settingwriter.WriteStartElement("headertext")
settingwriter.WriteString(dgv.Columns(i).HeaderText)
settingwriter.WriteEndElement()
settingwriter.WriteStartElement("displayindex")
settingwriter.WriteString(dgv.Columns(i).DisplayIndex.ToString())
settingwriter.WriteEndElement()
settingwriter.WriteStartElement("visible")
settingwriter.WriteString(dgv.Columns(i).Visible.ToString())
settingwriter.WriteEndElement()
settingwriter.WriteEndElement()
Next
settingwriter.WriteEndElement()
settingwriter.WriteEndDocument()
settingwriter.Close()
End Sub
End Module
If the user is reopening the form I used the below (Q/A code) to rearrange Datagridview column as pervious :
Public Sub ReadDataGridViewSetting(ByVal dgv As DataGridView, ByVal FileName As String, ByRef Frm_name As Form)
Dim xmldoc As XmlDocument = New XmlDocument()
Dim xmlnode As XmlNodeList
Dim CMSN_ToolName As String
Dim Var_file_Chk As String = "C:\Users\<user>\Desktop\temp\" & FileName & ".xml"
If System.IO.File.Exists(Var_file_Chk) = True Then
Dim fs As FileStream = New FileStream(Var_file_Chk, FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
xmlnode = xmldoc.GetElementsByTagName("column")
For i As Integer = 0 To xmlnode.Count - 1
Dim columnName As String = xmlnode(i).ChildNodes.Item(0).InnerText.Trim()
Dim width As Integer = Integer.Parse(xmlnode(i).ChildNodes.Item(1).InnerText.Trim())
Dim headertext As String = xmlnode(i).ChildNodes.Item(2).InnerText.Trim()
Dim displayindex As Integer = Integer.Parse(xmlnode(i).ChildNodes.Item(3).InnerText.Trim())
Dim visible As Boolean = Convert.ToBoolean(xmlnode(i).ChildNodes.Item(4).InnerText.Trim())
dgv.Columns(columnName).Width = width
dgv.Columns(columnName).HeaderText = headertext
dgv.Columns(columnName).DisplayIndex = displayindex
dgv.Columns(columnName).Visible = visible
Next
fs.Close()
End If
End Sub
Now what I need is that a Function or Sub for the Itemmenu. If a Particular column is Visible in the datagridview then the particular Itemmenu should be checked else it would be unchecked. I need this function when Itemmenu is being displayed / opened.
what I tried just (for sample) in Itemmenu opening is like
Private Sub ColumnsToolStripMenuItem_DropDownOpening(sender As Object, e As EventArgs) Handles ColumnsToolStripMenuItem.DropDownOpening
If DGV_CompList.Columns("DGC_Est").Visible = True Then
Dim CMSN_ToolName = MS_CV_Est.Name
Dim unused As ToolStripMenuItem = New ToolStripMenuItem(CMSN_ToolName) With {
.Checked = True
}
End If
End Sub
DGV_CompList -> DataGridView
DGC_Est -> Column Name of datagridview
MS_CV_Est -> - ToolStripMenuItem which need to checked
(Note: I will be changing the MenuItem Name to Match Datagrid Column name for Sync)
But the ToolStripMenuItem is not getting checked.
Actually I need function / Sub where I will be able to pass the grid name and the Menuname and loop through the grid columns and check if the column is visible or not if the particular column is visible then I need to check that item in the itemmenu.
I am requesting for the sub / function because it can be used for any toolstripmenuitem in any form.
Thanks and Regards.
As per #Jimi's hint, assigned each required Menuitem's Tag property with the datagridview column name and created the below sub / function :
Public Sub Fun_ToolStripMenuItem_Check(ByVal dgv As DataGridView, ByVal TS_Menu_Items As ToolStripItemCollection)
For Each item As ToolStripMenuItem In TS_Menu_Items.OfType(Of ToolStripMenuItem)
If Not item.Tag = "" Then
If dgv.Columns(item.Tag).Visible = True Then
item.Checked = True
Else
item.Checked = False
End If
End If
For Each submenu_item As ToolStripMenuItem In item.DropDownItems.OfType(Of ToolStripMenuItem)
If Not submenu_item.Tag = "" Then
If dgv.Columns(submenu_item.Tag).Visible = True Then
submenu_item.Checked = True
Else
submenu_item.Checked = False
End If
End If
Next
Next
End Sub
Note in the loop used - " OfType(Of ToolStripMenuItem) " because I have ToolStripSeparator between the Itemmenus.
On mouse over called the Sub by :
Private Sub MS_ColumnVisible_DropDownOpening(sender As Object, e As EventArgs) Handles MS_ColumnVisible.DropDownOpening
Fun_ToolStripMenuItem_Check(DGV_CompList, MS_CompDGV.Items)
End Sub
'DGV_CompList' - Datagridview Name and 'MS_CompDGV' - ContextMenuStrip Name
More important is that I did not assign any value to the Tag property to Menuitems which are not used show or hide the datagridview columns.

vb.net Postgresql Database, using DataTable and display bitmap in Datagridview

I am using a Postgresql, and I would like to store a status value. These values should be of type integer (0 = OK, 1 = Not OK e.g.).
But I don't want to display these values as integer in my datagridview, I would like to display some small icons or bitmaps.
But how am I able to do this?
If I am using a DataColumn with Bitmap Type, I can't use the Integer type in my database.
This is how I fill my DataTable with the SQL data.
dtRecord is assigned to my DataGridview.
sda = New NpgsqlDataAdapter(pgCommand)
sda.Fill(dtRecord)
This was a test - but I can't insert the integer values from the SQL Database
Dim column1 As DataColumn = New DataColumn("Status")
column1.DataType = GetType(Bitmap)
Can someone give me any hints?
Thanks!
This is a fully working sample of how to load an image from the disk based on a value in the grid and display that image. In addition to the code below, you will need to drop a DataGridView on to the form from the Designer
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
InitialiseGridView()
InitialiseDataTable()
DataGridView1.DataSource = RecordsDataTable
End Sub
Dim RecordsDataTable As DataTable
Private Sub InitialiseGridView()
DataGridView1.AutoGenerateColumns = False
AddHandler DataGridView1.CellFormatting, AddressOf DataGridView1_CellFormatting
DataGridView1.Columns.Clear()
Dim dgvImageColumn As New DataGridViewImageColumn()
dgvImageColumn.Name = "dgvImageColumn"
dgvImageColumn.DataPropertyName = "dgvImageColumn"
dgvImageColumn.HeaderText = "Status"
DataGridView1.Columns.Add(dgvImageColumn)
Dim dgvTextColumn As New DataGridViewTextBoxColumn
dgvTextColumn.Name = "dgvTextColumn"
dgvTextColumn.DataPropertyName = "dgvTextColumn"
dgvTextColumn.HeaderText = "Other Text"
DataGridView1.Columns.Add(dgvTextColumn)
End Sub
Private Sub InitialiseDataTable()
RecordsDataTable = New DataTable()
RecordsDataTable.Columns.Add("dgvImageColumn", GetType(Integer))
RecordsDataTable.Columns.Add("dgvTextColumn", GetType(String))
RecordsDataTable.Rows.Add({1, "one"})
RecordsDataTable.Rows.Add({0, "two"})
RecordsDataTable.Rows.Add({1, "three"})
End Sub
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
Dim thisDGV As DataGridView = DirectCast(sender, DataGridView)
If (thisDGV.Columns(e.ColumnIndex).Name = "dgvImageColumn") Then
Dim newImage As Image
If (e.Value.ToString() = "0") Then
newImage = Bitmap.FromFile("D:\Projects\Graphics\GreenDot.png")
Else
newImage = Bitmap.FromFile("D:\Projects\Graphics\RedDot.png")
End If
e.Value = newImage
e.FormattingApplied = True
End If
End Sub
End Class
This will give you a DataGridView that looks like:

Using corresponding value of picturebox to delete access record

Hey I've created a dictionary that I use to create pictureboxes. Each picturebox has a number, which I then want to use to remove the access record, corresponding to that number. So I've got the dictionary working, but how do I get the number that corresponds to each picturebox? Here is my code (everything is defined, like cardsdictionary as dictionary):
Public Sub bigpictureloader()
'Dim list As New List(Of String)(cardsdictionary.Keys)
Dim cardcount As Integer
cardcount = 0
counter += 1
cardcount = counter
'Dim cards As List(Of String) = New List(Of String)
cardsdictionary.Add(imageurltxt.Text, cardcount)
'Create a placeholder variable
Dim cardPictureBox As PictureBox
Dim pair As KeyValuePair(Of String, Integer)
'Loop through every selected card URL
For Each pair In cardsdictionary
'Create a new PictureBox
cardPictureBox = New PictureBox()
cardPictureBox.Size = New Size(100, 100)
cardPictureBox.SizeMode = PictureBoxSizeMode.Zoom
cardPictureBox.WaitOnLoad = False
AddHandler cardPictureBox.Click, AddressOf imagehandler
'Add the PictureBox to the Form
Me.Controls.Add(cardPictureBox)
'MsgBox(cardsdict.Values.ToString)
If imageurltxt.Text = "" Then
cardPictureBox = Nothing
Else
cardPictureBox.LoadAsync(pair.Key)
TableLayoutPanel1.Controls.Add(cardPictureBox, 0, 0)
End If
Next
End Sub
Private Sub testdelete()
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
'pair.value is what I think will work, but doesn't currently
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(pair.value)
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
this is my imagehandler!!!
Private Sub imagehandler(Sender As Object, e As EventArgs)
testdelete()
End Sub
You can use the Tag property of the PictureBox to store the ID. You populate this property when you create the PictureBox.
In your handler you can do something like this:
Private Sub imagehandler(Sender As Object, e As EventArgs)
Dim myPictureBox As PictureBox = CType(sender, PictureBox)
'Now you can access myPictureBox.Tag and pass it into your delete function
Dim id As Integer = -1
If Int32.TryParse(myPictureBox.Tag, id) = True Then
testdelete(id)
End If
End Sub
Private Sub testdelete(id As Integer)
'THIS SAVES TO THE DEBUG ACCESS DATABASE!!!!!
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = FULL YUGIOH ACCESS DATABASE.accdb;")
Using command As New OleDbCommand("Delete From cmon11 Where ID= #ID;", conn)
'pair.value is what I think will work, but doesn't currently
command.Parameters.Add("#ID", OleDbType.Integer).Value = id
conn.Open()
command.ExecuteNonQuery()
End Using
End Using
End Sub
testdelete doesn't know which imasge you want to delete. Using Michael's suggestion you want:
command.Parameters.Add("#ID", OleDbType.Integer).Value = CInt(Me.Tag)
By the way your use of counter and cardcount can be cleaned up substantially.

DatagridView VB.Net, thread safety

So i have this DataTable i have to show in a datagridview.
To do this i used to do the following line in the form_load
Me.Datagridview1.datasource = DT
It will work if i have to add a few rows, but when i add enough to make the scrollbar in the datagridview appear, it will freeze de program. No exceptions are thrown but my program will freeze and i think it is because im learning how to use threads.
Here i start listening another program that will send strings and i have to split them and put them into rows inside a datatable, and then show them.
Private Vstm As Stream
Dim tcp As New TcpClient
Dim DT As New DataTable("Acciones")
Dim Inter As New Interprete
Private Sub Conectar_Click(sender As Object, e As EventArgs) Handles Button1.Click
tcp.Connect("192.168.1.143", 8050)
Vstm = tcp.GetStream()
Dim VtcpThd As New Thread(AddressOf LeerSocket)
'Se arranca el subproceso.
VtcpThd.Start()
End Sub
Here in LeerSocket ill do the reading
Private Sub LeerSocket()
Dim VbufferDeLectura() As Byte
VbufferDeLectura = New Byte(100) {}
While True
'Se queda esperando a que llegue algĂșn mensaje.
Vstm.Read(VbufferDeLectura, 0, VbufferDeLectura.Length)
'Se evalĂșa que llega en la cabecera del mensaje.
Me.Inter.interpretar(Encoding.ASCII.GetString(VbufferDeLectura))
End While
End Sub
Here it is the class interprete, that will try to understand the string.
Public Class Interprete
Property Codigo As String
Property Cotizacion As Integer
Property Cabecera As String
Private VAcciones As DataTable
Public Property Acciones() As DataTable
Get
Return VAcciones
End Get
Set(ByVal value As DataTable)
VAcciones = value
End Set
End Property
Public Sub interpretar(Data As String)
Me.Cabecera = Nothing
Me.Codigo = Nothing
Dim buff() As String = Split(Data, "!!")
Dim arr() As String = Split(buff(0), "||")
Me.Cabecera = arr(0)
Me.Codigo = arr(1)
Select Case Cabecera
Case "COT"
Cotizaciones(arr)
End Select
End Sub
Public Sub Cotizaciones(M As String())
Dim DR As DataRow = Acciones.NewRow
Dim buffer(3) As Object
buffer(0) = ""
buffer(1) = 0
buffer(2) = M(1)
buffer(3) = M(2)
DR.ItemArray = buffer
Acciones.Rows.Add(DR)
End Sub
End Class
How can i use the datagridview safely?
Also can you guys recomend any books for vb?
You should invoke that data table action on the GUI thread:
Me.BeginInvoke(New Action(Sub()
Dim DR As DataRow = Acciones.NewRow
Dim buffer(3) As Object
buffer(0) = ""
buffer(1) = 0
buffer(2) = M(1)
buffer(3) = M(2)
DR.ItemArray = buffer
Acciones.Rows.Add(DR)
End Sub))

value of type 'cfeedback' cannot be converted to 'system.collections.arraylist'

Firstly, i have a grdData at my main page. After choosing the data i want and went to another page using
Request.QueryString("id")
In that page i would like to make another grdData using the
Request.QueryString("id")
but came upon an error by
Value of type 'cfeedback' cannot be converted to 'system.collections.arraylist'
Below are my codes
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objArrayList As New ArrayList
Dim objCDBFeedback As New CDBFeedback
Dim intGuestID2 As Integer
intGuestID2 = Request.QueryString("id")
objArrayList = objCDBFeedback.getFeedBack(intGuestID2)
grdResult.DataSource = objArrayList
grdResult.DataBind()
grdResult.HeaderRow.BackColor = Drawing.Color.AliceBlue
grdResult.RowStyle.BackColor = Drawing.Color.BlanchedAlmond
grdResult.AlternatingRowStyle.BackColor = Drawing.Color.LightSalmon
grdResult.Columns(0).Visible = True
End Sub
My Function
Public Function getFeedBack(ByVal pintGuestID1 As Integer) As CFeedback
Dim objCmd As New MySqlCommand
Dim objCn As New MySqlConnection(connectionString)
Dim objAdapter As New MySqlDataAdapter
Dim strSQL As String = ""
Dim objDs As New DataSet
Dim objDataRow As DataRow
strSQL = "SELECT * FROM tblFeedback WHERE strGuestCodeFB=" & pintGuestID1
objCmd.CommandText = strSQL
objCmd.Connection = objCn
objAdapter.SelectCommand = objCmd
objCn.Open()
objAdapter.Fill(objDs, "tblFeedback")
objDataRow = objDs.Tables("tblFeedback").Rows(0)
Dim objCFeedback As New CFeedback
objCFeedback.Feedback = objDataRow.Item("strGuestCompanyTI")
objCn.Close()
Return objCFeedback
End Function
My Class
Public Class CFeedback
Private strGuestCodeFB As Integer
Private strFeedBackFB As String
Public Property GuestId() As String
Get
Return strGuestCodeFB
End Get
Set(ByVal value As String)
strGuestCodeFB = value
End Set
End Property
Public Property Feedback() As String
Get
Return strFeedBackFB
End Get
Set(ByVal value As String)
strFeedBackFB = value
End Set
End Property
End Class
So is it possible to have a grdData base on querystring?
The very first thing that you need to do is edit your code behind and add the following two lines at the top:
Option Explicit On
Option Strict On
This will show you at least one error: assigning a type of CFeedback to a type of ArrayList.
You will need to determine what the appropriate resolution to this is, but I suspect that you want to return an ArrayList or generic List from GetFeedback instead of just the one item.
So, among other changes, you will want to change pageload to look something like:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objCDBFeedback As New CDBFeedback
Dim intGuestID2 As Integer
intGuestID2 = CInt(Request.QueryString("id"))
Dim cValues As System.Collections.Generic.List(Of CFeedback)
cValues = objCDBFeedback.getFeedBack(intGuestID2)
grdResult.DataSource = cValues
grdResult.DataBind()
grdResult.HeaderRow.BackColor = Drawing.Color.AliceBlue
grdResult.RowStyle.BackColor = Drawing.Color.BlanchedAlmond
grdResult.AlternatingRowStyle.BackColor = Drawing.Color.LightSalmon
grdResult.Columns(0).Visible = True
grdResult.Visible = cValues.Count <> 0
End Sub
And the getFeeback method to look something like:
Public Function getFeedBack(ByVal pintGuestID1 As Integer) As System.Collections.Generic.List(Of CFeedback)
Dim cValues As New System.Collections.Generic.List(Of CFeedback)
Using objCn As New MySqlConnection(connectionString)
Using objCmd As New MySqlCommand
Dim strSQL As String = ""
strSQL = "SELECT * FROM tblFeedback WHERE strGuestCodeFB=" & pintGuestID1
objCmd.CommandText = strSQL
objCmd.Connection = objCn
objCn.Open()
Using oReader As MySqlDataReader = objCmd.ExecuteReader
Do While oReader.Read
Dim objCFeedback As New CFeedback
objCFeedback.Feedback = oReader.Item("strGuestCompanyTI")
cValues.Add(objCFeedback)
Loop
End Using
objCn.Close()
End Using
End Using
Return cValues
End Function