Dim SiparisOnayi As String
Dim SiparisDurumu As String
Dim SiparisIli As String
Dim SiparisOdemeYontemi As String
Dim SiparisKargoFirmasi As String
Dim SiparisSatisKanali As String
Dim a1, a2, a3, a4, a5, a6, a7, soncom As String
If ComboBox1.Text = Nothing Then
a1 = Nothing
Else
SiparisOnayi = ComboBox1.Text
a1 = " and Siparis_Onay = SiparisOnayi"
End If
If ComboBox2.Text = Nothing Then
a2 = Nothing
Else
SiparisDurumu = ComboBox2.Text
a2 = " and Siparis_Durumu = SiparisDurumu "
End If
If ComboBox3.Text = Nothing Then
a3 = Nothing
Else
SiparisIli = ComboBox3.Text
a3 = " and Musteri_IL = SiparisIli "
End If
If ComboBox4.Text = Nothing Then
a4 = Nothing
Else
a4 = " and Kullanici_Kodu = SiparisKullanicisi"
End If
If ComboBox5.Text = Nothing Then
a5 = Nothing
Else
SiparisOdemeYontemi = ComboBox5.Text
a5 = " and Odeme_Yontemi = SiparisOdemeYontemi"
End If
If ComboBox6.Text = Nothing Then
a6 = Nothing
Else
SiparisKargoFirmasi = ComboBox6.Text
a6 = " and Kargo_Adi = SiparisKargoFirmasi"
End If
If ComboBox7.Text = Nothing Then
a7 = Nothing
Else
SiparisSatisKanali = ComboBox7.Text
a7 = " and Satis_Kanali = SiparisSatisKanali"
End If
soncom = "SELECT * FROM `Siparisler` WHERE `Siparis_Tarihi` BETWEEN #d1 and #d2" & a1 & a2 & a3 & a4 & a5 & a6 & a7 & ", connection"
Try
Dim command As New MySqlCommand(soncom)
command.Parameters.Add("#d1", MySqlDbType.DateTime).Value = DateTimePicker2.Value
command.Parameters.Add("#d2", MySqlDbType.DateTime).Value = DateTimePicker3.Value
Dim table As New DataTable
Dim adapter As New MySqlDataAdapter(command)
adapter.Fill(table)
DataGridView1.DataSource = table
Label12.Text = "Toplam " & table.Rows.Count & " Kayıt bulundu ve gösteriliyor."
myconnection.close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Error : fill: SelectCommand connection property has not been initialized
How can I fix my code?
The & ", connection" at the end of this line looks wrong to me:
soncom = "SELECT ..." & a1 & ... a7 & ", connection"
But also, you need a connection object in addition to a command and an adapter, the way the WHERE clause is currently assembled would be extremely vulnerable to sql injection issues if it worked at all, but it won't because the combobox values are never actually interpolated into the final string, and the code is vulnerable to leaving the connection hanging open if an exception is thrown during the call to Fill().
This should fix all of those issues (once you fill in the connection string):
Dim table As New DataTable
Using connection As New MySqlConnection("connection string here")
Using command As New MySqlCommand("", connection)
Using adapter As New MySqlDataAdapter(command)
Dim sql As String = "SELECT * FROM `Siparisler` WHERE `Siparis_Tarihi` BETWEEN #d1 and #d2"
If Not string.IsNullOrWhitespace(ComboBox1.Text) Then
sql += " and Siparis_Onay = #SiparisOnayi"
command.Parameters.AddWithValue("#SiparisOnayi", ComboBox1.Text)
End if
If Not string.IsNullOrWhitespace(ComboBox2.Text) Then
sql += " and Siparis_Durumu = #SiparisDurumu"
command.Parameters.AddWithValue("#SiparisDurumu", ComboBox2.Text)
End If
If Not string.IsNullOrWhitespace(ComboBox3.Text) Then
sql += " and Musteri_IL = #SiparisIli"
command.Parameters.AddWithValue("#SiparisIli", ComboBox3.Text)
End If
If Not string.IsNullOrWhitespace(ComboBox4.Text) Then
sql +" and Kullanici_Kodu = #SiparisKullanicisi"
command.Parameters.AddWithValue("#SiparisKullanicisi", ComboBox4.Text)
End If
If Not string.IsNullOrWhitespace(ComboBox5.Text) Then
sql += " and Odeme_Yontemi = #SiparisOdemeYontemi"
command.Parameters.AddWithValue("#SiparisOdemeYontemi", ComboBox5.Text)
End If
If Not string.IsNullOrWhitespace(ComboBox6.Text) Then
sql += " and Kargo_Adi = #SiparisKargoFirmasi"
command.Parameters.AddWithValue("#SiparisKargoFirmasi", ComboBox6.Text)
End If
If Not string.IsNullOrWhitespace(ComboBox7.Text) Then
sql += " and Satis_Kanali = #SiparisSatisKanali"
command.Parameters.AddWithValue("#SiparisSatisKanali", ComboBox7.Text)
End If
command.CommandText = sql
command.Parameters.Add("#d1", MySqlDbType.DateTime).Value = DateTimePicker2.Value
command.Parameters.Add("#d2", MySqlDbType.DateTime).Value = DateTimePicker3.Value
Try
adapter.Fill(table)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Using
DataGridView1.DataSource = table
Label12.Text = $"Toplam {table.Rows.Count} Kayıt bulundu ve gösteriliyor."
Related
I have a datagridview (unbound) which is populated from MS SQL Server database.
During the loop of reading information from DB and adding rows to the datagridview1 i get this message :“The connection was not closed. The connection's current state is open” .
' Here is the code
Private Sub ShowMSR_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim col As New CalendarColumn() With {.HeaderText = "ROS Date"}
DataGridView1.Columns.Insert(5, col)
Dim col_1 = New DataGridViewTextBoxColumn
col_1.Name = "Date"
DataGridView1.Columns(5).DefaultCellStyle.Format = "dd/MM/yyyy"
Dim strsqlcommand As String = "SELECT * FROM MSR Where MSR_ID='" & MSRID & "'"
Dim dr As SqlDataReader
Dim sqlcommand = New SqlCommand(strsqlcommand, Form1.SQL_conn)
Dim itemcode As String = ""
Dim Desc As String = " "
Dim qty As String = " "
Dim un As String = " "
Dim AC As String = ""
Dim comm As String = ""
Dim rdate As Date
strsqlcommand = "Select Item_Code, Quantity, Unit, Item_Description, AC_No, ROS_time, Coment_RO From ITEMS Where MSR_ID
= '" & MSRID & "'"
sqlcommand.CommandText = strsqlcommand
dr = sqlcommand.ExecuteReader()
While dr.Read()
itemcode = dr(0).ToString
qty = dr(1).ToString
un = dr(2).ToString
Desc = dr(3).ToString
AC = dr(4).ToString
If IsDBNull(dr(5)) Then
rdate = CDate("1990/1/1")
Else
rdate = CDate(dr(5))
End If
comm = dr(6).ToString
Dim row As String() = New String() {itemcode, qty, un, Desc, AC, rdate, comm}
Me.DataGridView1.Rows.Add(row) '<---Here occur the problem
End While
dr.Close()
If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()
Catch ex As Exception
' the exception is never triggered
MsgBox(ex.Message)
If (Form1.SQL_conn.State = ConnectionState.Open) Then Form1.SQL_conn.Close()
End Try
End Sub
I was wondering if it was possible to filter down data from a table using multiple values from a checkboxlist? (or any other way) I have a checkboxlist and a gridview and when you check on of the boxes it does show the right data in the gridview but the problem arises when I try to check multiple values. It seems to search for the first checked value and then ignores the rest. You'd think it'd be simple! Perhaps it is. Here is my attempt below.
CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim strSQL As New System.Text.StringBuilder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
FillGridView()
End If
End Sub
Private Sub FillGridView()
Dim strMyConn As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
Using MyConn As New SqlClient.SqlConnection(strMyConn)
MyConn.Open()
Dim cmd As New SqlClient.SqlCommand(strSQL.ToString, MyConn)
cmd.Connection = MyConn
cmd.CommandType = CommandType.Text
Try
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
If Me.GridView1.Visible = False Then Me.GridView1.Visible = True
Catch ex As Exception
Me.GridView1.Visible = False
End Try
End Using
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
If c <> 0 Then
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
End If
End Sub
End Class
Refactor this section to create a WHERE IN statement so it checks to see if the value is found among any item checked
Before
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
After
Dim params As StringBuilder = New StringBuilder()
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
params.Append("'")
params.Append(CheckBoxList1.Items(i).Text)
If i < Me.CheckBoxList1.Items.Count Then
params.Append("',") // don't append a comma if it's the last item
End If
End If
Next
strSQL.Append("SELECT Project.* FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID WHERE Keyword.Keyword in (")
strSQL.Append(params.ToString()) // append comma delimited values that make up where in statement
strSQL.Append("')") // close where in statement
FillGridView()
i populate items in listview and when i click the command button i will add the item in the list in the database and if an item from the list hasn't been checked out it will delete the item from the populated list below is my code.
Dim y As Integer
Dim a As String
y = ListView2.Items.Count
While y >= 0
a = ListView2.Items.Item(y).Text
y = y - 1
Dim TMP_SQL_VAL As String = "select count([Check-Out]) from tbl_list1 where barcode = '" + a + "'"
locconn.Open()
command = New SqlCommand(TMP_SQL_VAL, locconn)
Dim READER As SqlDataReader
READER = command.ExecuteReader()
READER.Read()
If READER(0) = 0 Then
MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
clear_text()
ListView2.Items.Remove(y)
Else
READER.Close()
Dim READER2 As SqlDataReader
Dim TMP_SQL_VAL2 = "select [Check-In] from tbl_list1 where barcode = '" + a + "' and [User] = '" + rsuser + "'"
Dim cmd = New SqlCommand(TMP_SQL_VAL2, locconn)
READER2 = cmd.ExecuteReader
READER2.Read()
If READER2(0) Is Nothing Then
MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
clear_text()
ListView2.Items.Remove(y)
End If
end if
locconn.Close()
End While
Catch ex As Exception
MsgBox(ex.Message)
localconn.ShowDialog()
Finally
locconn.Close()
End Try
Try to check if the value of y is < 0, if it is then nothing to process terminate it
Dim y As Integer
Dim a As String
y = ListView2.Items.Count - 1 'Reduce 1
If y < 0 Then return 'If no item then terminate
While y >= 0
a = ListView2.Items.Item(y).Text
'y = y - 1 'Moved to last line before End While
Dim TMP_SQL_VAL As String = "select count([Check-Out]) from tbl_list1 where barcode = '" + a + "'"
locconn.Open()
command = New SqlCommand(TMP_SQL_VAL, locconn)
Dim READER As SqlDataReader
READER = command.ExecuteReader()
READER.Read()
If READER(0) = 0 Then
MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
clear_text()
ListView2.Items.Remove(y)
Else
READER.Close()
Dim READER2 As SqlDataReader
Dim TMP_SQL_VAL2 = "select [Check-In] from tbl_list1 where barcode = '" + a + "' and [User] = '" + rsuser + "'"
Dim cmd = New SqlCommand(TMP_SQL_VAL2, locconn)
READER2 = cmd.ExecuteReader
READER2.Read()
If READER2(0) Is Nothing Then
MsgBox("Barcode: " & a & "is still Inside", MsgBoxStyle.Exclamation)
clear_text()
ListView2.Items.Remove(y)
End If
end if
locconn.Close()
y -= 1 'Move here so the value is decremented before the While statement
End While
Catch ex As Exception
MsgBox(ex.Message)
localconn.ShowDialog()
Finally
locconn.Close()
End Try
i am importing excel file in datagridview below is my code
'ofdImport.Filter = "Excel Files (*.xls)|*.xls"
ofdImport.FileName = ""
If ofdImport.ShowDialog(Me) = Windows.Forms.DialogResult.Cancel Then
Exit Sub
End If
txtPath.Text = ofdImport.FileName
If txtPath.Text <> "" Then
chkItemList.Visible = True
dgvImportData.Visible = True
pnlDataMsg.Visible = False
dgvImportData.Columns.Clear()
chkItemList.Items.Clear()
Try
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & txtPath.Text & " '; Extended Properties=Excel 8.0;")
Dim excelSelect As New OleDbCommand
Dim excelAdp As New OleDbDataAdapter
Dim excelSchemaDt As DataTable
Dim dset As New DataSet
If conExcel.State Then conExcel.Close()
conExcel.Open()
excelSelect.Connection = conExcel
excelSchemaDt = conExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim sheetName As String = excelSchemaDt.Rows(0)("TABLE_NAME").ToString()
excelSelect.CommandText = "select * from [" & sheetName & "] "
excelAdp.SelectCommand = excelSelect
excelAdp.TableMappings.Add("Table", "TestTable")
excelAdp.Fill(dset)
dgvImportData.DataSource = dset.Tables(0)
Dim i As Integer
Dim q(dgvImportData.Columns.Count()) As String
For i = 0 To (dgvImportData.Columns.Count - 1)
q(i) = (dgvImportData.Columns(i).HeaderText.ToString())
Next i
conExcel.Close()
i = 0
Dim a As String = ""
'Dim q(frmImportWizard.gridImport.Columns.Count()) As String
For i = 0 To dgvImportData.Columns.Count - 1
a = dgvImportData.Columns(i).HeaderText.ToString()
'CheckedListBox1.Items.Add(a)
chkItemList.Items.Add(a)
Next i
chkAll.Visible = True
chkAll.Checked = False
lblColumnData.Visible = True
Catch ex As Exception
'MsgBox(ex.Message, MsgBoxStyle.Information)
End Try
End If
excel file contains phone nos for eg "9874532146/8456663225" in one colms and also i have "98455566966" in same colmns
the problem here is my code is not reading the phone numbers
without "/" its going blank in grid
please help
replaced connection string
Dim conExcel As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source='" & txtPath.Text & "';Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""")
Im getting the following exception on vb.net. I have trouble solving this error:
Error 5: Index and length must refer to a location within the string.Parameter name: length.
here is my code :
Private Sub attemptedNumbersNew2(ByVal date_start As DateTime, ByVal date_end As DateTime, ByVal port As String, ByVal team As String)
Dim con As New ADODB.Connection
Dim recordS As New ADODB.Recordset
Dim sql As String = "some query...."
Try
con.Open(connectStringA)
recordS.Open(sql, con)
If recordS.EOF Then
Else
Do While Not recordS.EOF
Dim temp As String
If name4number.Contains(lastAttempted) Then
temp = name4number.Item(lastAttempted)
Else
temp = lastAttempted
End If
If attemptedNames.Equals("NONE") Or attemptedNames.Equals("") Then
attemptedNames = temp
ElseIf Not temp.Equals("") Then
attemptedNames = attemptedNames & " - " & temp
End If
If agentsHashOffered.Contains(temp & "_" & team) Then
agentsHashOffered.Item(temp & "_" & team) = agentsHashOffered.Item(temp & "_" & team) + 1
Else
agentsHashOffered.Add(temp & "_" & team, 1)
End If
If recordS.Fields(2).Value >= oldDate Then
If answeringNumber.Equals("NONE") Then
answeringNumber = recordS.Fields(4).Value
If answeringNumber.Substring(0, 1).Equals("9") Then
answeringNumber = answeringNumber.Substring(1, 10)
End If
callDuration = -1
End If
disconnectionTime = recordS.Fields(3).Value
Else
End If
If attempted.Equals("NONE") Then
attempted = recordS.Fields(4).Value
If attempted.Substring(0, 1).Equals("9") Then
attempted = attempted.Substring(1, 10)
End If
attemptedCount = attemptedCount + 1
lastAttempted = attempted
Else
temp = recordS.Fields(4).Value
If temp.Substring(0, 1).Equals("9") Then
temp = temp.Substring(1, 10)
End If
attempted = attempted & " - " & temp
attemptedCount = attemptedCount + 1
lastAttempted = temp
End If
recordS.MoveNext()
Loop
End If
con.Close()
con = Nothing
recordS = Nothing
Catch ex As Exception
MsgBox("Error #" & Err.Number & ": " & Err.Description)
End Try
End Sub
It was working fine the other day, but suddenly I started getting this error.
any helps are welcome
THANK YOU in Advance