2017-05-31 69 views
1

我有SQL數據庫表以下數據:指數超出範圍。必須是非負數且小於集合的大小。參數名:指數-6

BillNo Particular  Price  Unit  Amount  Taxamount  Tax 
2905  Airfreight  100.000 100  10000.000  0.000  0.000 
2905  Customs  4500.00 1   0.000  4500.000 675.000 
2906  THC   250.000 1   0.000  250.000  38.000 
2906  XYZ   5000.00 1  5000.000  0.0000 0.0000 

在一個窗口的形式我有一個由比爾號搜索名爲Tbblbillto.Text文本框和一個DataGrid。當我在文本框中鍵入賬單號碼時,如何使SQL表格中的數據根據​​賬單號碼進行過濾,然後將其放入數據網格中?

*Data Grid Table* 
**Particular  Price   Unit   Amount  Taxamount  Tax** 

Private Sub Tbblbillto_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Tbblbillto.TextChanged 
     Dim Cmd As New SqlClient.SqlCommand 
     Dim Con As New SqlClient.SqlConnection 
     Dim Rd As SqlDataReader 
     Con.ConnectionString = "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbase;Integrated Security=True;Pooling=False" 
     Cmd.Connection = Con 
     Con.Open() 
     Dim Row As New DataGridViewRow 
     Dim Int As Integer 
     Row = Dgvbillsa.Rows(Int) 
     Cmd.CommandText = "Select * from BillDetails Where BillNo = '" & Tbblbillto.Text & "'" 
     Rd = Cmd.ExecuteReader 
     Rd.Read() 
     If Rd.HasRows Then 
      Row.Cells(0).Value = Rd.Item("Particular") 
      Row.Cells(1).Value = Rd.Item("Price") 
      Row.Cells(2).Value = Rd.Item("Unit") 
      Row.Cells(3).Value = Rd.Item("Amount") 
      Row.Cells(4).Value = Rd.Item("TaxAmount") 
      Row.Cells(5).Value = Rd.Item("Tax") 
     End If 
    End Sub 
+2

我的我的,看所有的SQL注入漏洞。 – Will

+0

我不瞭解你的觀點 –

+0

如果用戶輸入'',會發生什麼?將表格BillDetails放入文本框中? –

回答

1

您可以使用DataTable將數據加載直接進入DataGridView,或者至少這是我會怎麼做。

執行SQL命令時,應但是使用的參數。這是爲了減少語法問題,但更重要的是停止SQL注入。有關詳細信息,請參閱Bobby Tables

我也會考慮實施Using

有時你的代碼需要非託管資源,如文件句柄,COM包裝或SQL連接。當你的代碼與他們完成A使用塊保證處置的一個或多個這樣的資源。這使它們可供其他代碼使用。

隨着改變你的代碼看起來類似這樣:

Dim dt As New DataTable 
Using con As New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbase;Integrated Security=True;Pooling=False"), 
     cmd As New SqlCommand("SELECT * FROM BillDetails WHERE BillNo = @BillNo", con) 

    con.Open() 

    cmd.Parameters.Add("@BillNo", SqlDbType.[Type]).Value = Tbblbillto.Text 

    dt.Load(cmd.ExecuteReader()) 

End Using 

Dgvbillsa.DataSource = dt 

請注意,我用SqlDbType.[Type]。你會希望與您已在數據庫上使用的數據類型來代替[Type]

這會將數據直接載入您的DataGridView。根據DataGridView的 設置,您可能需要對列進行一些更改。

0

這裏是我的問題的答案:

Cmd.CommandText = "Select Particular, Price, Unit, Amount, TaxAmount, Tax from BillDetails Where BillNo = '" & Tbblbillto.Text & "' GROUP BY [Particular], [Price], [Unit], [Amount], [TaxAmount], [Tax]" 
Rd.Close() 
Rd = Cmd.ExecuteReader 
While Rd.Read() OrElse (Rd.NextResult()) 
    If Rd.HasRows Then 
     Dgvbillsa.Rows.Add(Rd.Item("Particular"), Rd.Item("Price"), Rd.Item("Unit"), Rd.Item("Amount"), Rd.Item("TaxAmount"), Rd.Item("Tax")) 
相關問題