Search database based on datagridview column? - vb.net

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

Related

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

Search Data from Database and Display in unbound but predefined column Datagridview VB.Net

i want to search data from SQL database and display in pre defined columns of datagridview. following code i used for that:-
For i As Integer = 0 To DataGridView1.Rows.Count - 1
qry = "select * from Transs where DocNo='" & TextBox1.Text & "'"
cmd = New SqlCommand(qry, con)
con.Open()
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.Read Then
ComboBox1.Text = dr("CostCenter")
TextBox2.Text = dr("TransactionID")
DataGridView1.Rows(i).Cells(0).Value = dr("AccountID")
DataGridView1.Rows(i).Cells(1).Value = dr("AccountName")
DataGridView1.Rows(i).Cells(2).Value = dr("AccountType")
DataGridView1.Rows(i).Cells(3).Value = dr("Debit")
DataGridView1.Rows(i).Cells(4).Value = dr("Credit")
DataGridView1.Rows(i).Cells(5).Value = dr("Text")
End If
Next
con.Close()
But the problem is i am getting data in first row of datagridview only. Where is the mistake in this code?

Displaying multiple records

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.

Executing update query inside loop

cmd = New SqlCommand("select enrollment,total_fee,discount,net_fee from stu_dtl", openConnection())
' dr = cmd.ExecuteReader
adpt = New SqlDataAdapter(cmd)
adpt.Fill(ds, "stu_dtl")
dt = ds.Tables("stu_dtl")
For i = 0 To dt.Rows.Count - 1
cmd = New SqlCommand("update stu_dtl set net_fee = '" & (Val(dt.Rows(i).Item("total_fee")) - Val(dt.Rows(i).Item("discount"))) & "' where enrollment = '" & dt.Rows(i).Item("enrollment") & "'", openConnection())
cmd.ExecuteNonQuery()
Next
when I execute this code for more than 150 records "Nothing happens"......what am i doing wrong??is there any other way to update??
I'm not sure what you are doing wrong. But try this code. If an error occur it ensure rollback of the database. Note that I assume that the datatype of the net_fee and enrollment columns are Integer.
Using connection As SqlConnection = New SqlConnection("TODO: Set connection string.")
Dim table As DataTable = New DataTable("stu_dtl")
Dim [error] As Exception = Nothing
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "SELECT [enrollment], [total_fee], [discount], [net_fee] FROM [stu_dtl];"
Using adapter As New SqlDataAdapter(command)
adapter.Fill(table)
End Using
End Using
Using transaction As SqlTransaction = connection.BeginTransaction()
Try
Dim net_fee As Integer = 0
Dim enrollment As Integer = 0
For Each row As DataRow In table.Rows
net_fee = (CInt(row.Item("total_fee")) - CInt(row.Item("discount")))
enrollment = CInt(row.Item("enrollment"))
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "UPDATE [stu_dtl] SET [net_fee] = #net_fee WHERE [enrollment] = #enrollment;"
command.Parameters.AddWithValue("#net_fee", net_fee)
command.Parameters.AddWithValue("#enrollment", enrollment)
command.ExecuteNonQuery()
End Using
Next
transaction.Commit()
Catch ex As Exception
[error] = ex
transaction.Rollback()
End Try
End Using
If (Not table Is Nothing) Then
table.Dispose()
table = Nothing
End If
If (Not [error] Is Nothing) Then
Throw [error]
End If
End Using
Edit
Come to think of it, you might want to change the net_fee column to a computed column. The formula would simply be ([total_fee] - [discount]).

How do I catch an SQL exception in a VB.NET 2010 code?

Okay, I am building a VB.NET system but I'm having troubles in catching an SQL exception in some parts of my code. In short, I am using a SELECT sql query to retrieve a particular record and I want to determine whether a record exist in a MSAccess database so that I don't retrieve 0 rows. 0 rows will lead to an exception during printing to a TextField. The following is a sample code I'm working on:
If txSearch.Text = "" Then
MsgBox("Please type the user id or use the barcode reader to scan", MsgBoxStyle.OkOnly, "Search Field Empty")
End If
'ElseIf txSearch.Text != "" Then
If txSearch.Text <> "" Then
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim dt As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim de As OleDb.OleDbDataAdapter
Dim sql As String
Dim sql1 As String
Dim temp_num As Integer
Dim cmd As New OleDb.OleDbCommand
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = new.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim search As String
search = txSearch.Text
MessageBox.Show("You are going to search for " + search + ". Click OK to continue.")
sql = "SELECT * FROM Student_Details WHERE Admin_No = '" & txSearch.Text & "'"
sql1 = "SELECT * FROM Laptop_Details WHERE Admin_No = '" & txSearch.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
de = New OleDb.OleDbDataAdapter(sql1, con)
'Dim check As Integer = sql.
'If check > 0 Then
'da.SelectCommand = cmd
ds = New DataSet("Student_Details")
da.Fill(ds, "Student_Details")
dt = New DataSet("Laptop_Details")
de.Fill(dt, "Laptop_Details")
'con.Close()
'If sql <> "" And sql1 <> "" Then
'If ds.Equals(1) And ds.Equals(1) Then
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
Dim com As New OleDb.OleDbCommand(sql, con)
Dim com1 As New OleDb.OleDbCommand(sql1, con)
Try
temp_num = com.ExecuteNonQuery
temp_num = com1.ExecuteNonQuery
Catch ex As IndexOutOfRangeException
Trace.WriteLine(ex.ToString)
End Try
con.Close()
'End If
'End If
End If
Try something like this:
if ds.Tables("Student_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
End if
if ds.Tables("Laptop_Details").Rows.Count > 0
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
End if
To help you with your comment I would do it like that:
if ds.Tables("Student_Details").Rows.Count > 0 And ds.Tables("Laptop_Details").Rows.Count > 0
txAdminNO.Text = ds.Tables("Student_Details").Rows(0).Item(0)
txName.Text = ds.Tables("Student_Details").Rows(0).Item(1)
txProgramme.Text = ds.Tables("Student_Details").Rows(0).Item(2)
cmbSStatus.SelectedText = ds.Tables("Student_Details").Rows(0).Item(3)
txSerial.Text = dt.Tables("Laptop_Details").Rows(0).Item(1)
txModel.Text = dt.Tables("Laptop_Details").Rows(0).Item(2)
else
MsgBox("The user with id "+txSearch.Text+" does not exist")
end if
Try to use try-catch statement:
Try
Your code here for your query statements.
Catch ex as Exception MsgBox(ex.Message)End Try