how do i connect a field from mysql database to my combobox ?
it shows an error .
"System.InvalidCastException: 'Conversion from string "place" to type 'Integer' is not valid.'"
Imports MySql.Data.MySqlClient
Public Class OpenNewMishap
Dim Conns As New Connections()
Private Sub OpenNewMishap_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillCombo()
End Sub
Function FillCombo() As String
Dim Reader As MySqlDataReader()
Dim table As New DataTable()
Dim command As New MySqlCommand("SELECT Place FROM `placesinparameter`", Conns.GetConnection())
Conns.OpenConnection()
command.ExecuteReader.Read()
ComboBox1.Items.Add(Convert.ToString(command.ExecuteReader("place")))
End Function
End Class
that works for me:
POTComboBox.DataSource = takala.Getplaces()
POTComboBox.ValueMember = "Number"
POTComboBox.DisplayMember = "place"
Related
I have a ComboBox that I use on multiple WinForms. Instead of dropping a ComboBox on each WinForm and then filling the ComboBox with data from a DataTable on each individual WinForm, couldn't I create a User Control (ComboBox) that has the data populated already and just use that UC on my Winforms?
Below is how I fill the data for each individual combobox now. (I have a public class for the sql stuff)
The Variable SQL comes from a Class called SQLControl. the Class has all the sql connection stuff.
Public Sub Fillcombobox()
sql.AddParam("#ExaminerType", 3)
sql.ExecQuery("MyStoredProcedure")
ComboBoxExaminer.ValueMember = "Examiner_ID"
ComboBoxExaminer.DisplayMember = "Last_Name"
ComboBoxExaminer.DataSource = sql.DBDT
End Sub
Private Sub MyWinform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call Fillcombobox()
End Sub
You can put a small Class Examiner
Public Class Examiner
Public Property Examiner_ID As Integer
Public Property Last_Name As String
Public Sub New(ID As Integer, lname As String)
Examiner_ID = ID
Last_Name = lname
End Sub
End Class
Then, when the first form loads, get the data in a list declared in a module so it can be accessed from any form in the application. Of course, you may have other things in the Module.
Module Module1
Public ExaminerData As New List(Of Examiner)
End Module
Private Sub MyWinform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillExaminerList()
ComboBoxExaminer.ValueMember = "Examiner_ID"
ComboBoxExaminer.DisplayMember = "Last_Name"
ComboBoxExaminer.DataSource = ExaminerData
End Sub
Any other form that needs the data to fill a combo box can use ExaminerData. You only call FillExaminerList once at the beginning of the application. There is only a single hit on the database.
Private OPConStr As String = "Your connection string."
Private Sub FillExaminerList()
Dim dt As New DataTable
Using cn As New SqlConnection(OPConStr),
cmd As New SqlCommand("MyStoredProcedure", cn)
cmd.Parameters.Add("#ExaminerType", SqlDbType.Int).Value = 3
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
For Each row As DataRow In dt.Rows
Dim ex As New Examiner(CInt(row("Examiner_ID")), row("Last_Name").ToString)
ExaminerData.Add(ex)
Next
End Sub
Trying to populate a set of data from datatable to Combobox on the basis of text entered in Combobox. But getting a System.Data.DataRow error in the Select method of datatable.
Following is the code which binds the datatable on Form Load and rebinds data on the call of Search method.
Note that the search has to be on Tab press not AutoComplete
Imports System.Data.SqlClient
Public Class Form1
Dim connection As SqlConnection = New SqlConnection()
Dim table As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LoadComboBox()
End Sub
Private Sub LoadComboBox()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select stage from sample", connection)
adp.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub Search()
Dim filteredTable As New DataTable
Dim filterRow As DataRow()
Dim str As String = ComboBox1.Text.Trim
filterRow = table.Select("stage like '%" & ComboBox1.Text.ToString & "%'")
'**Error in above table(datatable)**
For Each rw As DataRow In filterRow
filteredTable.ImportRow(rw)
Next
ComboBox1.DataSource = New BindingSource(filteredTable, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub ComboBox1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles ComboBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Search()
End If
End Sub
End Class
in your binding to combo box you have a data table already why are you using a binding source
why not just say ComboBox1.DataSource = filteredTable
Also i would advice you to use Key Value Pair rather than using Like easier binding
Like is regex search at SQL Server this is killing your Database and you are creating overhead over nothing
Key | Value >>
ID | Name
so taking this from another stack over flow for fast reference
gridview bind dropdownlist to List<keyvaluePair<int, string>>
you can bind a dictionary , datatable , dataview does not matter.
if you want to get text just say your dropdown.text for the ID value dropdown.value if you want to do something later to in the database.
You can make your drop down read only and when user types basically what he is typing is filtering according to what you have binded that way your text search can be made
var dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Home");
dictionary.Add(2, "Work");
dictionary.Add(3, "Mobile");
dictionary.Add(4, "Fax");
dropDown.DataTextField = "Value";
dropDown.DataValueField = "Key";
dropDown.DataSource = dictionary; //Dictionary<int, string>
dropDown.DataBind();
Tried it with a bit of Linq.
Private Sub Search()
Dim filteredTable As New DataTable
Dim str As String = ComboBox1.Text.Trim
Dim filterRows = (From row As DataRow In Table.AsEnumerable
Where row.Field(Of String)("Name").Contains(ComboBox1.Text)
Select row.Field(Of String)("Name")).ToList
ComboBox1.DataSource = filterRows
End Sub
Just substitute your column name for "Name"
https://imgur.com/a/gaXh4
Ok so I have a problem a really weird problem. So I created a new class which is a new type of TextBox. It keeps track of the objects created from it with the help of a list but. This all works, with for each I can get all objects of the class but when I want to convert the string from the TextBox into a integer I can't do it because it thinks its not convertable eventhought the string only consists out of number symbols
Code for Button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'TextBox1.Text = CInt(SumTextBox1.Text) + CInt(SumTextBox2.Text)
For Each item As SumTextBox In SumTextBox.sumList
Dim textItem As SumTextBox = item
TextBox1.Text = CInt(TextBox1.Text) + CInt(textItem.Text)
Next
End Sub
Public Class SumTextBox
Inherits TextBox
Public Shared sumList As New List(Of SumTextBox)
Sub New()
Size = New Size(90, 10)
sumList.Add(Me)
End Sub
End Class
Try using Convert.toInt32(TextBox1.Text) and the same for textitem.text
Could someone help here?
I need to extract data from a Database into a combolistbox in VB.net. I have got the data, but now find that The first and the 'x' line need to be removed from the combolistbox (they are validation entries for another software) and shouldn't be selected for this application.
I tried to simply remove the offending entries from lists by using :- cbCubeARivet.Items.RemoveAt(index), but had an error letting me know I cannot use "Items" with a DataSource.
I decided to send the data to a listbox, and then try to transfer the entries to the combolistbox. This then lead me to getting multiple entries of System.Data.DataRowView in the combolist box. To demonstrate my problem I include an example code modified from MSDN.
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Populate the list box using an array as DataSource.
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
'Use DataAdapter to fill DataTable
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
'original code from MSDN
'Dim USStates As New ArrayList()
'USStates.Add(New USState("Alabama", "AL"))
'USStates.Add(New USState("Washington", "WA"))
'USStates.Add(New USState("West Virginia", "WV"))
'USStates.Add(New USState("Wisconsin", "WI"))
'USStates.Add(New USState("Wyoming", "WY"))
'ListBox1.DataSource = USStates
' Set the long name as the property to be displayed and the short
' name as the value to be returned when a row is selected. Here
' these are properties; if we were binding to a database table or
' query these could be column names.
' Bind the SelectedValueChanged event to our handler for it.
AddHandler ListBox1.SelectedValueChanged, AddressOf ListBox1_SelectedValueChanged
' Ensure the form opens with no rows selected.
ListBox1.ClearSelected()
End Sub 'NewNew
Private Sub ListBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As EventArgs)
If ListBox1.SelectedIndex <> -1 Then
TextBox1.Text = ListBox1.SelectedValue.ToString()
' If we also wanted to get the displayed text we could use
' the SelectedItem item property:
' Dim s = CType(ListBox1.SelectedItem, USState).LongName
End If
End Sub
End Class 'ListBoxSample3
Public Class USState
Private myShortName As String
Private myLongName As String
Public Sub New(ByVal strLongName As String, ByVal strShortName As String)
Me.myShortName = strShortName
Me.myLongName = strLongName
End Sub 'NewNew
Public ReadOnly Property ShortName() As String
Get
Return myShortName
End Get
End Property
Public ReadOnly Property LongName() As String
Get
Return myLongName
End Get
End Property
End Class 'USState
I may not get this correct so here goes, the following uses mocked up data to display a string in both a ListBox and ComboBox where a integer is available by casting the current item as a DataRowView, access Row then access the data via Row.Field(Of Integer)("ID").
In the code I use a copy of the underlying DataTable for the ComboBox as using the same data table for listbox and combobox will cause one to traverse when is generally unwanted. The cast aspect would be done in another event but wanted to stay simple. Again I may not be on track here, let me know and can adjust to better suit your question.
Code using Option Infer On for the Linq anonymous statement which could be strongly typed too.
Dim dt As New DataTable
dt.Columns.Add(New DataColumn With {.ColumnName = "ID", .DataType = GetType(Integer)})
dt.Columns.Add(New DataColumn With {.ColumnName = "Name", .DataType = GetType(String)})
Dim data =
(
From M In System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
Where Not String.IsNullOrEmpty(M)).ToList.Select(
Function(monthName, index) New With
{
.ID = index, .Name = monthName
}
).ToList
For Each item In data
dt.Rows.Add(New Object() {item.ID, item.Name})
Next
ListBox1.DataSource = dt
ListBox1.DisplayMember = "Name"
ComboBox1.DataSource = dt.Copy
ComboBox1.DisplayMember = "Name"
Dim theTable As DataTable = CType(ComboBox1.DataSource, DataTable)
Dim theRow As DataRow = theTable.AsEnumerable _
.Where(
Function(row) row.Field(Of String)("Name") = "September") _
.FirstOrDefault()
If theRow IsNot Nothing Then
theTable.Rows.Remove(theRow)
End If
Thanks again #Karen Payne,
I used your code to lead me in the right direction.
I created a new application and added a textbox, and two Listboxes, then paste the code. To run you will need to point to your own Server, Database, and Table.
This is what I came up with. It is useful as this will give you the actual data in a useable form:-
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Collections
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' get the data
Dim SQLConnectionString As String = "Data Source=HL605\RIVWARE;Database=RIVWARE;Integrated Security=true;"
Dim mySQLConnection As New SqlConnection(SQLConnectionString)
' Populate the list box using an array as DataSource.
mySQLConnection.Open()
Dim SQLDataTable As New System.Data.DataTable
'Create new DataAdapter
Dim mySQLDataAdapter = New SqlDataAdapter("SELECT * FROM [Rivware].[dbo].[RivetTypes]", mySQLConnection)
mySQLDataAdapter.Fill(SQLDataTable)
ListBox1.DataSource = SQLDataTable
ListBox1.DisplayMember = "RivetType"
' remove validation data from list
Dim Count As Integer
Dim X As Integer
'get the column of data to search for
For Count = 0 To ListBox1.DataSource.Columns.Count - 1
X = InStr(ListBox1.DataSource.Columns.Item(Count).ToString, "Name")
If X <> 0 Then Exit For
Next
' now search for any invalid rows, in that column. those containing "---"
Dim TheTable As DataTable = CType(ListBox1.DataSource, DataTable)
Dim theRow As DataRow() = TheTable.Select()
Dim RowNumber As Integer
For RowNumber = 0 To UBound(theRow) - 1
If theRow(RowNumber).Item(Count).ToString <> "---" Then
' data is OK so transer it to the other listbox
ListBox2.Items.Add(theRow(RowNumber).Item(Count - 1).ToString)
End If
Next
ListBox2.ClearSelected()
End Sub 'NewNew
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
TextBox1.Text = ListBox2.SelectedItem.ToString()
End Sub
End Class 'ListBoxSample3
I get the following error when running this code. I am trying to query data out of my SQL database using parameters and appear to have most everything I need, but I can't quite figure out the error on this one. My debugging attempts have failed:
"Object reference not set to an instance of an object"
Option Strict Off
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Drawing
Imports System.IO
Public Class Form1
Dim thisConnection = New SqlConnection("Server=myserver;Database=myDatabase;User Id=username;Password=password")
Dim DBCommand As SqlCommand
Dim myReader As SqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
thisConnection.Open()
Console.WriteLine("Connect Open")
DBCommand.Parameters.AddWithValue("#dateOld", "20151215")
DBCommand.Parameters.AddWithValue("#dateNew", "20151231")
Dim myReader = DBCommand.ExecuteReader()
Dim fNextResult As Boolean = True
Dim fileName As String = "C:\Users\Documents\MomInt.txt"
DBCommand = New SqlCommand("*****SQL code*****")
Dim outputStream As StreamWriter = New StreamWriter(fileName)
'Get all values from the current item on the reader as long asRead() returns true...
Do While myReader.Read
'make an array the length of the available fields
Dim values(myReader.FieldCount - 1) As Object
'get all the field values
myReader.GetValues(values)
'write the text version of each value to a comma seperated string
Dim line As String = String.Join(",", values)
'write the csv line to the file
outputStream.WriteLine(line)
Loop
myReader.Close()
outputStream.Close()
Me.Text = "Success!"
Me.BackColor = Color.Chartreuse()
thisConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Failed!", MessageBoxButtons.AbortRetryIgnore)
End Try
End Sub
End Class