How to refresh form after selecting value from combobox - sql

I would like to know if it is possible to refresh the current windows form I am at after selecting another value from the combo box in order to display the details of that item onto several other textboxes?
So my table looks like
table name : program
program_id program_name program_desc
1 T1 desc1
This is the code i am using atm
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "pathway"
Dim dr As SqlDataReader
Dim prognamedesc As String
Dim filetypetxt As String
Dim prognamecombo As String
Dim filetypecombo1 As String
Dim command As New SqlCommand
Dim querycommand As New SqlCommand
connection.Open()
'THIS SECTION LOADS DATA FROM THE TABLES'
Try
command.Connection = connection
command.CommandType = CommandType.Text
command.CommandText = "select program_name,filetype from program order by program_name; select * from filetype"
querycommand.Connection = connection
querycommand.CommandType = CommandType.Text
querycommand.CommandText = "select program_name,program_desc , filetype from program where program_name like" & FiletypeComboBox1.SelectedItem & ""
dr = command.ExecuteReader
While dr.Read()
prognamecombo = dr(0)
Program_nameComboBox.Items.Add(prognamecombo)
End While
dr.NextResult()
While dr.Read()
filetypecombo1 = dr(0)
FiletypeComboBox1.Items.Add(filetypecombo1)
FiletypeComboBox1.SelectedItem = filetypecombo1
End While
dr.NextResult()
While dr.Read()
filetypetxt = dr(0)
FiletypeLabel1.Text = filetypetxt
End While
dr.NextResult()
While dr.Read()
prognamedesc = dr(0)
Program_descTextBox.Text = prognamedesc
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
I was wondering if this is doable using the current code?

To implement this you have to do two things, First put all your code inside a method and call it something like RefreshForm()
public void RefreshForm()
{
// your code and binding goes here
}
The second step is by using selected index changed event over combobox you just call the method that includes all your binding code.

Related

Filling a combobox using a query with a where command (VB.NET)

I have problems with filling a combobox.
I'm able to fill one whith a simple select query.
Now I want to fill a combobox with a query that inculdes a where command. I tried several solutions but none of them worked.
How can I fill a combobox with a query with a where statement?
My code so far is:
Public Function vulComboboxTesten(box As ComboBox, naam As String) As ComboBox
box.Items.Clear()
box.Items.Add(" ")
Dim query As String
query = "Select Sector from Onderaannemers where Naam_firma = #naam "
Debug.WriteLine(query)
Dim command As OleDbCommand
command = New OleDbCommand(query, connectie)
command.Connection.Open()
Dim datareader As OleDbDataReader
datareader = command.ExecuteReader
While datareader.Read
Dim item As New ComboBoxItem
item.Content = datareader("Sector")
box.Items.Add(item)
End While
command.Connection.Close()
Return box
End Function
Try this sir. i dont know how to translate my code into your type of coding. But just read the explanations.
Private Sub StoringDatainCombobox()
Try
Dim comboSource As New Dictionary(Of String, String)()
mkcon() 'this is just my sqlCon.Open
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
cmd.Connection = sqlCon
cmd.CommandText = "data_get" 'my query stored procedure.
'cotains something like this select * from tb1 where isactive = true
cmd.CommandType = CommandType.StoredProcedure
comboSource.Add(0, "") ' for blank item in the 1st value of combobox
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "key"
ComboBox1.Text = ""
rd = cmd.ExecuteReader
While (rd.Read)
comboSource.Add(rd("dataId"), rd("dataName"))
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "key"
ComboBox1.Text = ""
End While
sqlCon.Close()
Catch ex As Exception
MessageBox.Show("Failed." & ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
You can now display the data result of your query also with an id.
if you need how to get the id when user select an item in combobox just inform me.
Hope this will help you.

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

ExecuteReader() Object reference not set to an instance of an object error

I am trying to figure out why I am getting an error of 'Object reference not set to an instance of an object.' when my winforms code runs. I have set a breakpoint on the sql statement and stepped into the code and it shows as the line: Using dr = oledbCmd.ExecuteReader()
I am still learning vb.Net so would appreciate some help as to how to overcome this error. Many thanks
DBConnection.connect()
sql = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
Dim cmd As New OleDb.OleDbCommand
cmd.Parameters.AddWithValue("#p1", cmbCustomer.Text)
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
Using dr = oledbCmd.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
End Using
cmd.Dispose()
dr.Close()
oledbCnn.Close()
DBConnect module
Imports System.Data.OleDb
Module DBConnection
Public connetionString As String = My.Settings.storageConnectionString
Public oledbCnn As New OleDbConnection
Public oledbCmd As OleDbCommand
Public dr As OleDbDataReader
Public sql As String
Sub connect()
'connetionString = My.Settings.storageConnectionString
oledbCnn.ConnectionString = connetionString
oledbCnn.Open()
End Sub
End Module
I saw several mistakes. Look to the comments for reasons for the changes
Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
'.Net uses connection pooling, such that you're better using a new connection object for each query
'Also, a Using block will ensure the connection is closed, **even if an exception is thrown**
' The original code would leak connections when exceptions occured, eventually locking you out of the db
Using cn As New OleDb.OleDbConnection("Connection string here"), _
cmd As New OleDb.OleDbCommand(sql, cn) 'set CommandText BEFORE adding parameters
'Use explicit parameter types
cmd.Parameters.Add("?", SqlDbType.NVarChar, 50).Value = cmbCustomer.Text
cn.Open()
Using dr As OleDb.OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
dr.Close()
End Using
End Using
You have failed to properly bind the SqlConnection to the SqlCommand object.
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
End Using
See: MSDN
Edit: Requested adjustment to aid in clarity:
Using connection As New Data.SqlClient.SqlConnection
Dim sql As String = "SELECT * from Boxes WHERE Customer = ? AND Status = 'I'"
connection.Open()
Using command As New Data.SqlClient.SqlCommand(Sql, connection)
command.Parameters.AddWithValue("#p1", cmbCustomer.Text)
dr = command.ExecuteReader()
While dr.Read()
Dim LV As New ListViewItem
With LV
.UseItemStyleForSubItems = False
MediaTypeNames.Text = dr(1).ToString()
.SubItems.Add(dr(2).ToString())
End With
lvSelectRequestItems.Items.Add(LV)
End While
End Using
End Using
Your code should look something like that.
you have a fair amount of potential issues going on here.
1-you are using your dr variable twice. once before the using, which is probably causing your error. then again in for using, which does not look right because it is not the cmd variable used to execute the reader. so change this part of your code:
cmd.CommandText = sql
cmd.Connection = oledbCnn
dr = cmd.ExecuteReader
Using dr = oledbCmd.ExecuteReader()
to this:
cmd.CommandText = sql
cmd.Connection = oledbCnn
Using dr = cmd.ExecuteReader()
2-you are not showing if oledbCnn has been opened yet. I'm assuming your DBConnection.connect() function is doing this and olebCnn is a variable that function sets and opens
3-I'm not sure if the question mark in your query string will work. Even if it does you should replace it with the parameter name. so your query string should be:
sql = "SELECT * from Boxes WHERE Customer = #p1 AND Status = 'I'"
lastly you should probably show all the code for the sub(or function) this is for so we can get a full picture. example dr must be declared before the using else you would get a build error.

showing a sql coulmn data in a vb.net combobox

I want to show all the data in a specific column in one combobox and my code is just showing the last data in the column here is the code i am using
Dim connectionstring As String = "Data Source=localhost\SQLEXPRESS;InitialCatalog=Enginee;Integrated Security=True"
Try
Dim connection As New SqlClient.SqlConnection(ConnectionString)
Dim sqlquery As String
connection.Open()
MessageBox.Show("Open")
sqlquery = " Select PROJECT.PROJECT_CODE,PROJECT.PROJECT_NAME From PROJECT INNER JOIN ENGINEERS on ENGINEERS.ENGINEER_ID = ENGINEERS.ENGINEER_ID where ENGINEERS.FNAME = '" & Sign_In.TextBox1.Text & "' "
Dim selectcommand As New SqlClient.SqlCommand(sqlquery, connection)
Dim reader As SqlClient.SqlDataReader = selectcommand.ExecuteReader
Dim test As Boolean = reader.Read
While test = True
ComboBox1.Text = reader(0)
TextBox1.Text = reader(1)
test = reader.Read
End While
Catch ex As Exception
MessageBox.Show("Failed")
End Try
Instead of setting the .text of the ComboBox add the item.
ComboBox1.Items.Add(reader(0));
Setting the Text value will just set what the current item is, not adding them to the dropdown list.

Not able read the next record using datareader

I want to retrieve data from multiple tables and want to generate a crystal report. Hence i have created a new table and inserting values in it each time i need to generate the report. So i am using the following code to retrieve the data from those tables.
Code:
Private Sub gen_Report()
Dim dr, dr1, dr2 As OleDb.OleDbDataReader
Dim cmd, cmdDel, comm_inv1, comm_invuser As OleDb.OleDbCommand
If cnnOLEDB.State = ConnectionState.Closed Then
cnnOLEDB.Open()
End If
Dim strDelInsRp As String = ("DELETE FROM Inst_Report")
cmdDel = New OleDb.OleDbCommand(strDelInsRp, cnnOLEDB)
cmdDel.Parameters.AddWithValue("#chlno", cmbChal_no.Text)
cmdDel.ExecuteNonQuery()
Dim strSelIns As String = ("SELECT * FROM Installation_det where Chalan_No=#chlno")
cmd = New OleDb.OleDbCommand(strSelIns, cnnOLEDB)
cmd.Parameters.AddWithValue("#chlno", cmbChal_no.Text)
dr = cmd.ExecuteReader
Try
Do While dr.Read = True
mach_srno = dr("Machine_SrNo")
tft_srno = dr("TFT_SrNo")
chl_no = dr("Chalan_No")
usernm = dr("User_Name")
ins_dt = dr("Date_Of_Installation")
war_perd = dr("Warranty_Period")
war_till = dr("Warranty_Valid_Till")
Dim strSelInv1 As String = ("SELECT * FROM INVOICE_ONE where LAY_NO='VDC' AND CHL_NO=#chn_no ")
comm_inv1 = New OleDb.OleDbCommand(strSelInv1, cnnOLEDB)
comm_inv1.Parameters.AddWithValue("#chn_no", chl_no)
dr1 = comm_inv1.ExecuteReader
If dr1.Read = True Then
doc_no = dr1("DOCU_NO")
code_no = dr1("CODE_NO")
memb_nm = dr1("MEMB_NM")
Dim strSelInvUser As String = ("SELECT * FROM INVOICE_USER where CODE_NO=#code AND LAY_NO='VDC' AND DOCU_NO=#docno")
comm_invuser = New OleDb.OleDbCommand(strSelInvUser, cnnOLEDB)
comm_invuser.Parameters.AddWithValue("#code", code_no)
comm_invuser.Parameters.AddWithValue("#docno", doc_no)
dr2 = comm_invuser.ExecuteReader
If dr2.Read = True Then
User_add = dr2("ILEN2") & dr2("ILEN3") & dr2("ILEN4") & dr2("ILEN5")
End If
dr2.Close()
End If
dr1.Close()
Dim strInsRep As String = "INSERT INTO Inst_Report(Mach_srNo,TFT_srNo,Mem_nm,UserNm,Dt_Inst,War_Per,war_till,User_Address) VALUES (#mach_srno,#tft_no,#mem_nm,#uname,#inst_dt,#war_per,#war_till,#address)"
Dim comm_InsRep As OleDb.OleDbCommand = New OleDb.OleDbCommand(strInsRep, cnnOLEDB)
comm_InsRep.Parameters.AddWithValue("#mach_srno", mach_srno)
comm_InsRep.Parameters.AddWithValue("#tft_no", tft_srno)
comm_InsRep.Parameters.AddWithValue("#mem_nm", memb_nm)
comm_InsRep.Parameters.AddWithValue("#uname", usernm)
comm_InsRep.Parameters.AddWithValue("#inst_dt", ins_dt)
comm_InsRep.Parameters.AddWithValue("#war_per", war_perd)
comm_InsRep.Parameters.AddWithValue("#war_till", war_till)
comm_InsRep.Parameters.AddWithValue("#address", User_add)
comm_InsRep.ExecuteNonQuery()
Loop
dr.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
But the problem is that the datareader only reads for the first record even if I am using 'do While Loop'.
I have another question:
As the number of fields are more I want to generate report in Landscape orientation.
So how to change the orientation of report.
I am using Visual studio 2005 and MS-Access 2007. And programming language is VB.NET.
Regarding your data, I believe the standard way to get data from an OleDbDataReader is to use it to fill a datatable, try this:
Private Function GetDataTableUsingDataReader(ByVal command As OleDbCommand) As DataTable
Dim dataTable As DataTable = New DataTable
Using reader As OleDbDataReader = command.ExecuteReader
dataTable.Load(reader, LoadOption.OverwriteChanges)
End Using
Return dataTable
End Function
To get your crystal report to landscape, right click on the report in the designer, goto design => page setup. From here you can change the orientation.