Cascading ComboBoxes - sql

I am trying to create a cascading ComboBox that is populated from a SQL data set.
My problem is I am not getting any errors when compiling the code. but the two ComboBoxes are not populating as intended with data. Can you help me find where I am making the mistake?
Private Sub FillSalesPerson()
Dim strConnString As String
strConnString = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "select distinct Name,Salesperson_Code from dbo.View_Customers_With_Sales_People"
Dim objeDS As DataSet = New DataSet()
Dim dAdapter As New SqlDataAdapter
dAdapter.SelectCommand = cmd
DS.Open()
dAdapter.Fill(objeDS)
DS.Close()
ComboBox1.ValueMember = "Salesperson_Code"
ComboBox1.DisplayMember = "Name"
ComboBox1.DataSource = objeDS.Tables(0)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If ComboBox1.SelectedValue.ToString() <> " " Then
Dim Salesperson_Code As Integer = Convert.ToInt32(ComboBox1.SelectedValue.ToString())
FillStates(Salesperson_Code)
'ComboBox2.SelectedIndex = 0'
End If
End Sub
Private Sub FillStates(Salesperson_Code As Integer)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("con").ConnectionString
Dim DS As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.Connection = DS
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select [No_],[Company Name] from [dbo].[View_Customers_With_Sales_People] where (Salesperson_Code= #Salesperson_Code)"
cmd.Parameters.AddWithValue("#Salesperson_Code", Salesperson_Code)
Dim objDs As New DataSet()
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = cmd
DS.Open()
adapter.Fill(objDs)
DS.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ComboBox2.ValueMember = "[No_]"
ComboBox2.DisplayMember = "[Company Name]"
ComboBox2.DataSource = objDs.Tables(0)
End If
End Sub

Try changing ComboBox1.DataSource = objeDS.Tables(0) for ComboBox1.RowSource = objeDS.Tables(0)

Related

Multiple DataGridView on TabPages. vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
abc()
Refresh()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query As String = Nothing
Dim Query2 As String = Nothing
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query = "Select sMessage, iAlert FROM MAS_Alert"
Query2 = "SELECT REF_AlertPlate.sPlateNo, MAS_Alert.sMessage, REF_AlertPlate.iAlert, REF_AlertPlate.dStart, REF_AlertPlate.dEnd, REF_AlertPlate.sFrameNo FROM REF_AlertPlate INNER JOIN MAS_Alert ON MAS_Alert.iAlert=REF_AlertPlate.iAlert"
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query, conn)
adapter.SelectCommand = New SqlCommand(Query2, conn)
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
ComboBox1.Items.Clear()
DataGridView2.DataSource = ds.Tables(0)
DataGridView1.DataSource = ds.Tables(1)
ComboBox1.DataSource = Nothing
ComboBox1.Refresh()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "iAlert"
ComboBox1.DisplayMember = "sMessage"
Catch ex As Exception
End Try
conn.Close()
End Sub
How can I load the datagridView1? The only DataGridView that loads is the DataGridView2. Sorry if I'm wrong, I set the three queries in the formload. What should I do first?? The only query that loads is the Query and Query2Thank you in advance mates. Hope that you can help me.
I've created another sub for the DataGridView1 then call it in FormLoad
Sub Query3()
Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
Dim conn As New SqlConnection(con)
Dim Query3 As String = Nothing
Dim adapter As New SqlDataAdapter
Dim adapter1 As New SqlDataAdapter
Dim ds As New DataSet()
Dim table As New DataTable()
Dim cmd1 As New SqlCommand
Query3 = "SELECT iAlert, sMessage, dCreated, iCreatedBy FROM MAS_Alert"
Try
conn.Open()
adapter.SelectCommand = cmd
adapter.SelectCommand = New SqlCommand(Query3, conn)
adapter.Fill(ds)
adapter.Dispose()
cmd.Dispose()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
End Try
conn.Close()
End Sub
Problem Solved. Sorry if I made a mistake.

show database values in listbox when you open a form

I'm just new to vb.net.. Anyway, Is there a way when I open my form the items in my database will show up automatically?
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
list()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM Tbl", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(3) {}
Dim itm As ListViewItem
arr(0) = rdr("ID")
arr(1) = rdr("Name")
arr(2) = rdr("Brand")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
You can use below code
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Tbl")
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
End Using
End Using
End Using
Dim list As List(Of DataRow) = dt.AsEnumerable().ToList()
this code can convert direct data table to list.

Link Two Comboboxes vb net

Combobox2 values need to be changed when combobox1 changes value
Private Sub ComboBoxPodelba_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPodelba.SelectedIndexChanged
Dim myconnect As New SqlConnection
myconnect.ConnectionString = Common.connectionString
Dim mycommand2 As SqlCommand = New SqlCommand()
mycommand2.Connection = myconnect
Try
myconnect.Open()
mycommand2.CommandText = "select PodPodelbaIme from PodPodelba where PodelbaFK = '" + ComboBoxPodelba.SelectedValue.ToString + "'"
Dim reader2 As SqlDataReader
reader2 = mycommand2.ExecuteReader()
Dim dt2 As DataTable = New DataTable
dt2.Load(reader2)
ComboBoxPOdPodelba.ValueMember = "PodPodelbaIme"
ComboBoxPOdPodelba.DisplayMember = "PodPodelbaIme"
ComboBoxPOdPodelba.DataSource = dt2
Catch ex As Exception
End Try
End Sub
Try...
Private Sub Combo1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combo1.SelectedIndexChanged
Dim myconnect As New SqlConnection
myconnect.ConnectionString = Common.connectionString
Dim mycommand2 As SqlCommand = New SqlCommand()
mycommand2.Connection = myconnect
Try
myconnect.Open()
mycommand2.CommandText = "select PodPodelbaIme from PodPodelba where PodelbaFK = '" + Sender.SelectedValue.ToString + "'"
Dim reader2 As SqlDataReader
reader2 = mycommand2.ExecuteReader()
Dim dt2 As DataTable = New DataTable
dt2.Load(reader2)
Combo2.ValueMember = "PodPodelbaIme"
Combo2.DisplayMember = "PodPodelbaIme"
Combo2.DataSource = dt2
Catch ex As Exception
End Try
End Sub

Show my data from SSMS SQL into Visual Studio 2012 Datagrid View?

So I have this code in my form but when I try to click the search button to search for a name and show it into my datagrid view using the details from my sql database, it brings nothing. Just blank datagrid.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim tblClientDetails As New DataTable
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
With cmd
.Connection = CON
.CommandText = "select * from tblClientDetails where name = #name"
.CommandType = CommandType.Text
.Parameters.AddWithValue("#name", TextBox1.Text)
dr = .ExecuteReader
End With
While (dr.Read)
DataGridView1.DataSource = tblClientDetails
End While
My data in sql which i want to be shown in my datagrid below after searching from a textbox
http://i.stack.imgur.com/3J9lh.png
My form's data grid looks like this;
http://i.stack.imgur.com/QxmF5.png
try this..
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sqlCmd As New SqlCommand()
If CON.State = ConnectionState.Closed Then
CON.Open()
End If
sqlCmd.CommandText = "select * from tblClientDetails where name = #name"
sqlCmd.Connection = CON
sqlCmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader = sqlCmd.ExecuteReader()
Dim tblClientDetails As New DataTable()
tblClientDetails.Load(dr)
DataGridView1.DataSource = objDataTable
DataGridView1.DataBind()
CON.Close()
End Sub
Sample example to load a data reader to your data table and then data table to your grid is shown below.
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
Dim MyConnection As SqlConnection
Dim MyCommand As SqlCommand
Dim MyDataTable As DataTable
Dim MyReader As SqlDataReader
Dim CityParam As SqlParameter
MyConnection = New SqlConnection()
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("DSN_Northwind").ConnectionString
MyCommand = New SqlCommand()
MyCommand.CommandText = " SELECT * FROM CUSTOMERS WHERE CITY = #CITY "
MyCommand.CommandType = CommandType.Text
MyCommand.Connection = MyConnection
CityParam = New SqlParameter()
CityParam.ParameterName = "#CITY"
CityParam.SqlDbType = SqlDbType.VarChar
CityParam.Size = 15
CityParam.Direction = ParameterDirection.Input
CityParam.Value = "London"
MyCommand.Parameters.Add(CityParam)
MyCommand.Connection.Open()
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)
MyDataTable = New DataTable()
MyDataTable.Load(MyReader)
gvCustomers.DataSource = MyDataTable
gvCustomers.DataBind()
MyDataTable.Dispose()
MyCommand.Dispose()
MyConnection.Dispose()
End If
End Sub
Source available here

specified cast is not valid

Here is a code that retrieve values from the database, but my problem is that it throws out an exception saying "InvalidCastException was unhandled specified cast is not valid". I am now confused what went wrong, The code and the table stated below.
Here is the code:
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source =" & Application.StartupPath &
"\TestData.accdb; Persist Security info = false"
Public Conn As New OleDbConnection
Private Sub TestForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loard
Conn.ConnectionString = connstring
Conn.Open()
LoadValue( )
End Sub
Private Sub LoadValue( )
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
TextBox1.Text = reader.GetString(0)
i = TextBox1.Text + 1
TextBox1.Text = i
reader.Close()
End If
End With
End Sub
The table reference:
Exception Error:
I am really confused now on why the code does not work, any help and advice will be gladly accepted. Thanks in advance.
try this,
Private Sub LoadValue()
Dim i As Integer
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = "SELECT MAX(Guard_ID) FROM Guard"
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
Dim tmpVal As Object = reader.Item(0)
TextBox1.Text = IIf(IsDBNull(tmpVal), "0", tmpVal.ToString())
i = CInt(TextBox1.Text) + 1
TextBox1.Text = i.ToString()
reader.Close()
End If
End With
End Sub