Displaying multiple records - vb.net

Private Sub Line_Change2()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("Id")
Cmb1.Text = reader.Item("ProductCode")
Des1.Text = reader.Item("Description")
Qty1.Text = reader.Item("Qty")
TextBox2.Text = reader.Item("Id")
Cmb2.Text = reader.Item("ProductCode")
Des2.Text = reader.Item("Description")
Qty2.Text = reader.Item("Qty")
TextBox3.Text = reader.Item("Id")
Cmb3.Text = reader.Item("ProductCode")
Des3.Text = reader.Item("Description")
Qty3.Text = reader.Item("Qty")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I am new to vb coding just want to help with displaying multiple rows on multiple textboxes. Above code picks up Payroll Id from a textbox from another table and then it goes through dbo.Smline table below. I want to display the multiple records under the same payroll Id in different textboxes. This code doesn't seem to be working properly.

On your form you have three set of controls. Thus, you are able to display just up to three products for each clicked Payroll_id. Your code inserts the same value in all sets. Change your code to the following:
Private Sub Line_Change2()
ResetControls()
Dim cn As New SqlClient.SqlConnection("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
Using cn
cn.Open()
Dim cmd As New SqlClient.SqlCommand
Dim reader As SqlClient.SqlDataReader
Try
Dim sql As String
sql = "select Id,Payroll_Id,ProductCode,Description,Qty from dbo.SmLine where Payroll_Id ='" + Txt1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim counter as Integer = 1
While reader.Read
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Id").ToString()
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = reader.Item("ProductCode").ToString()
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Description").ToString()
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = reader.Item("Qty").ToString()
counter += 1
if counter =3 then Exit While
End While
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Public Sub ResetControls()
For counter = 1 to 3
CType(me.Controls.Find("TextBox" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Cmb" + CType(counter,String),False)(0),ComboBox).Text = ""
CType(me.Controls.Find("Des" + CType(counter,String),False)(0),TextBox).Text = ""
CType(me.Controls.Find("Qty" + CType(counter,String),False)(0),TextBox).Text = ""
Next
End Sub
The above code exits the reading when it has more than three products for a Payroll_id, because you just have three sets of controls. But if you could have more than three products for each clicked Payroll_id and you want to display all of them, then you have to build your controls dynamically.

Related

Search database based on datagridview column?

Database search based on a specific column of Datagrid View results in finding the first row in the search interval, and this row is not my goal ... Why does a row-by-row search find only the first row?
i am working with vb.net 2015 & sql server 2014
This is my attempt to write a search code
Please help me..
Try
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim row As DataGridViewRow = DataGridView1.Rows(i)
If DataGridView1.Rows.Count <> 0 Then
If CBool(row.Cells("انتخاب").Value) = True Then
Dim rd As SqlDataReader
Dim con As New SqlConnection()
con.ConnectionString = (ConfigurationManager.ConnectionStrings("constr").ConnectionString)
con.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT F_Takhsise_SatheTafzili_B_Moin.ID,F_Takhsise_SatheTafzili_B_Moin.Acckind,
F_Takhsise_SatheTafzili_B_Moin.StmoinName,
F_Takhsise_SatheTafzili_B_Moin.UkolCode,
F_Takhsise_SatheTafzili_B_Moin.UmoinName,
F_Takhsise_SatheTafzili_B_Moin.Code_Sathe5,
F_Takhsise_SatheTafzili_B_Moin.Sathe5,
F_Takhsise_SatheTafzili_B_Moin.Code_Sathe6,
F_Takhsise_SatheTafzili_B_Moin.Sathe6,
F_Takhsise_SatheTafzili_B_Moin.Id_F_AnvaeSanadeHesabdari,
F_Takhsise_SatheTafzili_B_Moin.name
from F_Takhsise_SatheTafzili_B_Moin
where F_Takhsise_SatheTafzili_B_Moin.name = '" & row.Cells(8).Value.ToString() & "'"
cmd.Connection = con
rd = cmd.ExecuteReader
If rd.HasRows = True Then
Do
While rd.Read()
ID_code_Sathe5 = rd("code_Sathe5").ToString
ID_acckind = rd("acckind").ToString
ID_ukolcode = rd("ukolcode").ToString
ID_F_Takhsise_SatheTafzili_B_Moin = rd("id").ToString
End While
Loop While rd.NextResult
End If
End If
End If
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try

I want a quick solution about adding a new row to datagraidview

I have a DataGridView and I'm adding a new row. But, when I add the new row it deletes the current row and replaces it.
This is the code
Try
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("SELECT ItemID, RTRIM(DishName),'1',Rate from Dish where ItemID like '" & TextBox1.Text & "' order by DishName", con)
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGridView1.Rows.Clear()
While (rdr.Read() = True)
DataGridView1.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3))
Dim num1 As Double
num1 = Val(DataGridView1.Rows(0).Cells("Qty").Value) * Val(DataGridView1.Rows(0).Cells("Rate").Value)
num1 = Math.Round(num1, 2)
DataGridView1.Rows(0).Cells("Amount").Value = num1
End While
TotalCalc()
Compute()
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
I am having a little problem following your question
Suggestion Don't tell us you want a quick solution
If you are changing the value in the DB use Update
Here is some code to add values to a DataGridView with SQLite
The SELECT statement is a little odd due to another issue in my Project
Just use your SELECT also Welcome to Stackoverflow
Private Sub ViewSearches()
Dim intID As Integer
Dim strCodeDesc As String
Dim strUIProject As String
Dim strCodeType As String
Dim rowCount As Integer
Dim maxRowCount As Integer
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand("", conn)
If gvTxType = "View" Then
cmd.CommandText = "SELECT * FROM CodeTable WHERE cvCodeType = #site"
cmd.Parameters.Add("#site", DbType.String).Value = gvSCT
ElseIf gvTxType = "All" Then
cmd.CommandText = "SELECT * FROM CodeTable"
End If
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
intID = CInt((rdr("CID")))
strCodeDesc = rdr("cvCodeDesc").ToString
strUIProject = rdr("cvUIProject").ToString
strCodeType = rdr("cvCodeType").ToString
dgvSelCode.Rows.Add(intID, strCodeDesc, strUIProject, strCodeType)
rowCount += 1
End While
dgvSelCode.Sort(dgvSelCode.Columns(3), ListSortDirection.Ascending)
End Using
If rowCount <= 12 Then
maxRowCount = 12 - rowCount
For iA = 1 To maxRowCount
dgvSelCode.Rows.Add(" ")
Next
End If
End Using
End Using
End Sub

autofilling textboxes with database data based on a primary key entry into another textbox

i have the code below, it works fine but whenever i insert a student number that does not exist in the table, the rest of the textboxes will keep displaying data from the previous existing entry. This happens even when the i delete everything in the student number textbox.
how can i change it such that the rest of the textboxes are cleared in case the student number textbox is blank or contains a student number that does not exist in the database?
Thanks in advance.
' Try
Dim mycommand As SqlCommand = New SqlCommand()
Dim datareader As SqlDataReader = Nothing
myconnection.Open()
Dim query As String
query = " select StudentNo,Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "' and (class = 'Senior 5A' or Class ='Senior 5S' or Class='Senior 6A' or class='Senior1 6S')"
mycommand = New SqlCommand(query, myconnection)
datareader = mycommand.ExecuteReader()
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
End If
End While
myconnection.Close()
' Catch ex As Exception
'MessageBox.Show(ex.Message)
' End Try`
Add an else condition to reader and clear text boxes in that module.
While datareader.Read
If datareader IsNot Nothing Then
' TxtStudentNo.Text = datareader.Item("StudentNo")
TxtName.Text = datareader.Item("FullName")
TxtYear.Text = datareader.Item("Year")
TxtTerm.Text = datareader.Item("Term")
TxtClass.Text = datareader.Item("Class")
else
TxtName.Text = ""
TxtYear.Text = ""
TxtTerm.Text = ""
TxtClass.Text = ""
End If
hope theres no big deal more than this.
I finally changed my code to the one below and it's doing exactly what i want.
Private Sub getData()
Dim dt As New DataTable()
myconnection.Open()
Dim Mycommand As New SqlCommand("select Fullname,Year,Term,Class from StudentRegistration where StudentNo = '" & TxtStudentNo.Text & "'", myconnection)
Dim sqlDa As New SqlDataAdapter(Mycommand)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TxtName.Text = dt.Rows(0)("FullName").ToString()
TxtYear.Text = dt.Rows(0)("Year").ToString()
Else
TxtName.Text = ""
TxtYear.Text = ""
End If
myconnection.Close()
End Sub

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.

retrieving image from database

I'm working on my project which displays a list of employee. here, the information and picture of the employee will be shown. my project can now show the list of employees in the listbox and when I double click on an employee, his/her profile will be shown on a textbox. my problem is that i can't make their pictures to show in the picturebox. I already stored their picture on a table in my database along with their id, name, and profile. It only shows the picture of the first employee on the table. can anybody help me?
here's what I already done:
I populated the listbox:
Call Connect()
With Me
STRSQL = "Select employee_name from Employees"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
reader.Close()
adptr.SelectCommand = myCmd
adptr.Fill(dt)
lstEmployee.DisplayMember = "employee_name"
lstEmployee.ValueMember = "employee_id"
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
here's how I show the info on textbox
Dim FileSize As UInt32
Dim mStream As New System.IO.MemoryStream()
Dim arrImage() As Byte = mStream.GetBuffer()
FileSize = mStream.Length
Dim cmd As New MySqlCommandBuilder
Call Connect()
With Me
STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
reader = myCmd.ExecuteReader
If (reader.Read()) Then
txtName.Text = reader("employee_name")
txtProfile.Text = reader("profile")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
adptr.SelectCommand = myCmd
dt = New DataTable
adptr = New MySqlDataAdapter("select picture from Employees", myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
You miss the where clause is must be like to search a one employee to view there image.
adptr = _
New MySqlDataAdapter("select picture from Employees " + _
"where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
P.S.: You must study the LINQ (Language-Integrated Query) for better approach.