2012-05-24 17 views
-1
public partial class HardwareInformation : BaseForm 
{ 
    string sWhere = ""; 
    public HardwareInformation() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection objConn1 = new SqlConnection("Data Source=192.168.0.203;Initial Catalog=costing;User ID=sa;[email protected]"); 
     if (searchtextbox.Text.Trim() != "") 
     { 
      sWhere = "Where Srno '" + searchtextbox.Text;  
     } 

     SqlDataAdapter objAdapter = new SqlDataAdapter(@"Select distinct [Srno] ,[Employee Name] , [Department] , [Thin Client] , [Desktop] , [Lcd] , [Moniter] , [Printer] , [Ups] from [dbo].[HardwareDetail] " + sWhere + "", objConn1); 
     DataTable objTable = new DataTable(); 
     objAdapter.Fill(objTable); 
     dataGridView1.DataSource = objTable; 
     dataGridView1.Columns[0].Width = 25; 
     for (int i = 1; i < dataGridView1.Columns.Count; i++) 
     { 
      dataGridView1.Columns[i].ReadOnly = true; 
     } 
    } 
+0

文本框中是否有單引號? –

+0

不,沒有quatation標記 –

+0

旁邊的一點點,但是:你應該在搜索框文本傳遞到SQL查詢之前真的做一些sanitisation,否則你的應用程序是開放的SQL注入攻擊(假設此代碼進入生產)。 – Moonshield

回答

2

使用

"Where Srno = '" + searchtextbox.Text + "'"; 

你以後的TextBox文本之後Srno和關閉單引號忘記=跡象之後。

在SqlDataAdapter的創建,在最後一次使用

"[Ups] from [dbo].[HardwareDetail] " + sWhere, objConn1); 

而且BTW請beaware SQL注入攻擊線。

+1

接受答案是謝謝你............只是開玩笑。 ;) –

1

在文本框文本後面缺少=缺少符號和結束引用。因此它應該是

"Where Srno = '" + searchtextbox.Text +"'"; 
1

您的代碼易受SQL Injection attacks影響。你應該永遠不要直接插入用戶輸入到你的SQL,而不消毒。你真的需要改變一個參數化查詢:

SqlDataAdapter objAdapter = new SqlDataAdapter(@"Select distinct [Srno] ,[Employee Name] , [Department] , [Thin Client] , [Desktop] , [Lcd] , [Moniter] , [Printer] , [Ups] from [dbo].[HardwareDetail] WHERE Srno = @srno", objConn1); 

// Change the length and dbtype to match your needs 
objAdapter.Parameters.Add("@srno", SqlDbType.NChar, 15, searchtextbox.Text); 

DataTable objTable = new DataTable(); 
objAdapter.Fill(objTable); 

這可以節省您從注入漏洞,同時也消除了需要逃避的報價和其他特殊字符。