populate combobox from the selected item of other combobox - vb.net

I'm creating a form in which a user has to give a State name and a City name. Where the city depends on the state.
Code for populating the city:
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from statestab order by `state` ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
ComboBoxstate.DataSource = ds.Tables(0)
ComboBoxstate.ValueMember = "stateid"
ComboBoxstate.DisplayMember = "state"
Code for the city :
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
Dim st As Integer
st = ComboBoxstate.SelectedValue.ToString()
sql = "SELECT * from citytab where stateid=st order by `cityname` ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
citycombo.DataSource = ds.Tables(0)
citycombo.ValueMember = "cityid"
citycombo.DisplayMember = "cityname"
In the combobox, when the selected city is changed, I call the city load function to populate the city combobox.
But I'm cant populate the city combobox.

You will need handler in Selected_Index_Changed in your State Combobox. From there call your routine to load up the City, in the SQL for city you would need to do
where stateid=" & comboBox1.SelectedValue.ToString()

Here is full text, Note that is can be much better but I tried to keep your syntax in tact:
Private Sub cboState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboState.SelectedIndexChanged
Load_Cities()
End Sub
Private Sub Load_States()
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from tblState order by StateName ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
cboState.DataSource = ds.Tables(0)
cboState.ValueMember = "stateid"
cboState.DisplayMember = "statename"
End Sub
Private Sub Load_Cities()
On Error Resume Next
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from tblCity where StateID = " & cboState.SelectedValue.ToString() & " order by CityName ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
cboCity.DataSource = ds.Tables(0)
cboCity.ValueMember = "CityID"
cboCity.DisplayMember = "CityName"
End Sub

Related

How do i show my data from a table with specific position to a combobox? example is this

How do i show my data from a table in database with specific position to a combobox? example is this
Example
Only with the President Position candidates will appear on combobox1 from table1
Only with the VPresident Position candidates will appear on combobox2 from table1
and so on...
im stuck with this on combobox1 which is called prescombo
code
Private Sub prescombo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles prescombo.SelectedIndexChanged
Try
Dim query As String = "SELECT * FROM Candidates WHERE Position = President"
Using con As SqlConnection = New SqlConnection("Data Source=EXPOOKY;Initial Catalog=SchoolDB;Integrated Security=True")
Using cmd As SqlCommand = New SqlCommand(query, con)
Dim datapter As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim datable As DataTable = New DataTable()
datapter.Fill(datable)
prescombo.DisplayMember = "CandidateName"
prescombo.ValueMember = "CandidateID"
If datable.Rows.Count > 0 Then
If datable.Rows(3)("Position") = "President" Then
presparty.Text = datable.Rows(3).Item("Position").ToString
End If
End If
End Using
End Using
Catch ex As Exception
End Try
End Sub
This is what i tried based on my logic and its not working
If you're filtering the data using a WHERE clause in the query then there's no need to check the records in the result set. Just populate the DataTable and bind it.
Dim query = "SELECT * FROM Candidates WHERE Position = 'President'"
Dim connectionString = "Data Source=EXPOOKY;Initial Catalog=SchoolDB;Integrated Security=True"
Using adapter As New SqlDataAdapter(query, connectionString)
Dim table As New DataTable
adapter.Fill(table)
With prescombo
.DisplayMember = "CandidateName"
.ValueMember = "CandidateID"
.DataSource = table
Endf With
End Using

i have change the background color of row in datagridview if already expired the medicine?

i have change the background color of row in datagridview if already expired the medicine?
con.Open()
Dim query As String
query = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date"
command = New MySqlCommand(query, con)
readers = command.ExecuteReader
Dim count As Integer
count = 0
While readers.Read
count = count + 1
End While
con.Close()
If count = 0 Then
MsgBox("no expiration")
Else
Dim SQL As String = ""
Dim da As MySqlDataAdapter = Nothing
Dim dt As New DataTable
SQL = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date"
command = New MySqlCommand(SQL, con)
End If
Ok fist of all you need to load de grid with the database data in this way:
con.Open()
Dim query As String
Dim da As new MySqlDataAdapter
Dim dt As New DataTable
query = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date is not null"
command = New MySqlCommand(query, con)
da.SelectCommand = cm
da.Fill(dt)
dgv1.datasource = dt
Then you have to set the color in the cellformating event:
Private Sub dgv1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgv1.CellFormatting
If dgv1.Rows(e.RowIndex).Cells("expiration_date").Value < now Then
dgv1.Rows(e.RowIndex).cells("expiration_date").Style.BackColor = Color.Red
End If
I do not understand what you are trying to do or how you are going to load the grid. any way to change the color of a column all you have to do is:
dgv1.Columns("columnsName").DefaultCellStyle.BackColor = Color.Red

Dataset to a table in database

I have a Dataset called 'ds' and I want to put that dataset into one of my tables in my sql database. I cannot seem to find a solution for this. How would I go about putting the dataset into a table? Any help would be greatly appreciated!
Code so far. Dataset that is created from user input:
Dim ds As DataSet = CreateNewDataSet()
Dim entries As New List(Of String())
Console.WriteLine("Enter first name: ")
firstName = Console.ReadLine()
Console.WriteLine("Enter last name: ")
lastName = Console.ReadLine()
entries.Add({firstName, lastName})
entries.ForEach(Sub(x) ds.Tables(0).Rows.Add(x))
I'm only using one table, 'Person' with the fields 'firstname' and 'lastname'.
Trying to insert dataset into table Person:
Using connection = New OleDbConnection("connectionstring")
connection.Open()
Dim adapter = New OleDbDataAdapter()
Dim myQuery As String = String.Empty
myQuery &= "INSERT INTO Applicant (strFirstName, strLastName)"
myQuery &= "VALUES(?, ?)"
adapter.InsertCommand = New OleDbCommand(myQuery, connection)
adapter.InsertCommand.Parameters.AddWithValue("#strFirstName", firstName)
adapter.InsertCommand.Parameters.AddWithValue("#strLastName", lastName)
adapter.Update(ds)
End Using
This is the solution:
Private Function CreateObject(ds as DataSet)
Dim connection as OdbcConnection = new OdbcConnection(conString)
connection.Open()
Dim adapter as OdbcDataAdapter = new OdbcDataAdapter("select * from Table", connection)
ds = new DataSet("DefaultName")
adapter.FillSchema(ds, SchemaType.Source, "Table")
adapter.Fill(ds, "Table")
Dim table as DataTable
table = ds.Tables("Table")
Dim row as DataRow = Nothing
row = table.NewRow()
row("field1") = varField1
row("field2") = varField2
table.Rows.Add(row)
Return ds
End Function

The LEVEL clause includes a reserved word or argument that is misspelled or missing, or the punctuation is incorrect vb.net

Dim connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\vladut.moraru\Desktop\TCO Orders\02_Template_BOM.xls;Extended Properties=""Excel 8.0;HDR=YES;"""
Dim pram As OleDbParameter
Dim dr As DataRow
Dim olecon As OleDbConnection
Dim olecomm As OleDbCommand
Dim olecomm1 As OleDbCommand
Dim oleadpt As OleDbDataAdapter
Dim ds As DataSet
Try
olecon = New OleDbConnection
olecon.ConnectionString = connstring
olecomm = New OleDbCommand
olecomm.CommandText = "Select Level, F_N, Name, Rev from [BOM$]"
olecomm.Connection = olecon
olecomm1 = New OleDbCommand
olecomm1.CommandText = "Insert into [BOM$] " & "(Level, F_N, Name, Rev) values " & "(#FName, #LName, #Age, #Phone)"
olecomm1.Connection = olecon
pram = olecomm1.Parameters.Add("#FName", OleDbType.VarChar)
pram.SourceColumn = "Level"
pram = olecomm1.Parameters.Add("#LName", OleDbType.VarChar)
pram.SourceColumn = "F_N"
pram = olecomm1.Parameters.Add("#Age", OleDbType.VarChar)
pram.SourceColumn = "Name"
pram = olecomm1.Parameters.Add("#Phone", OleDbType.VarChar)
pram.SourceColumn = "Rev"
oleadpt = New OleDbDataAdapter(olecomm)
ds = New DataSet
olecon.Open()
oleadpt.Fill(ds, "BOM")
If IsNothing(ds) = False Then
dr = ds.Tables(0).NewRow
dr("Level") = "Raman"
dr("F_N") = "Tayal"
dr("Name") = 24
dr("Rev") = 98989898
ds.Tables(0).Rows.Add(dr)
oleadpt = New OleDbDataAdapter
oleadpt.InsertCommand = olecomm1
Dim i As Integer = oleadpt.Update(ds, "BOM")
End If
Catch ex As Exception
Finally
olecon.Close()
olecon = Nothing
olecomm = Nothing
oleadpt = Nothing
ds = Nothing
dr = Nothing
pram = Nothing
End Try
I want tot write into tamplate excel with column Level, F_N, Name, Rev and my code generate that error from title. I want to insert some value in my excel but on line oleadpt.Fill(ds, "BOM") give me that error. I put a pic with excel file. The sheet name is BOM
My question is, where i miss to generate that code? I write wrong my columns or my connection?

DataGridView's RowCount is zero

I am having problems with code below:
For x As Integer = 0 To family_grid.RowCount
family_composition = family_grid.Rows(x).Cells(0).Value
age = family_grid.Rows(x).Cells(1).Value
status = family_grid.Rows(x).Cells(2).Value
relation = family_grid.Rows(x).Cells(3).Value
educational_attainment = family_grid.Rows(x).Cells(4).Value
occupation = family_grid.Rows(x).Cells(5).Value
income = family_grid.Rows(x).Cells(6).Value
dbConnect.Open()
Dim str1 As String = "INSERT INTO tbl_general_intake_family(id, family_composition, age, status, relation, educational_attainment, occupation, income)values(id, family_composition, age, status, relation, educational_attainment, occupation, income)"
Dim da As New OleDbDataAdapter()
Dim ds As New DataSet()
Dim com As New OleDb.OleDbCommand(str1, dbConnect)
com.Parameters.AddWithValue("id", var_document_id)
com.Parameters.AddWithValue("family_composition", family_composition)
com.Parameters.AddWithValue("age", age)
com.Parameters.AddWithValue("status", status)
com.Parameters.AddWithValue("relation", relation)
com.Parameters.AddWithValue("educational_attainment", educational_attainment)
com.Parameters.AddWithValue("occupation", occupation)
com.Parameters.AddWithValue("income", income)
com.ExecuteNonQuery()
com.Dispose()
dbConnect.Close()
Next
The for loop never executes because family_grid.RowCount is returning a value of zero.
In the form_load event, I populate the DataGridView using the following code:
Dim mycon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + My.Application.Info.DirectoryPath + "\mswd-rms.mdb")
mycon.Open()
Dim mycomm As New OleDbCommand("SELECT * FROM tbl_general_intake_family WHERE id=" & main_general_intake.document_id, mycon)
Dim da As New OleDbDataAdapter()
da.SelectCommand = mycomm
Dim ds As New DataSet()
da.Fill(ds)
family_grid.Columns.Clear()
family_grid.ReadOnly = true
family_grid.DataSource = ds.Tables(0)
family_grid.Columns(0).HeaderText = "ID"
family_grid.Columns(1).HeaderText = "Name"
family_grid.Columns(2).HeaderText = "Age"
family_grid.Columns(3).HeaderText = "Status"
family_grid.Columns(4).HeaderText = "Relation"
family_grid.Columns(5).HeaderText = "Educational Attainment"
family_grid.Columns(6).HeaderText = "Occupation"
family_grid.Columns(7).HeaderText = "Income"
There is no way the RowCount should be zero given the grid is populated with a single Row in the Form_Load. RowCount should return 1.
To workaround the issue save the datatable to a private form level variable and use its Row.Count.
private dtCurrentGrid As DataTable
..
dtCurrentGrid = ds.Tables(0)
..
For x As Integer = 0 To dtCurrentGrid.Rows.Count