2014-09-13 59 views
0

我想在我的應用程序中進行數據庫搜索,用戶將選擇列並輸入搜索詞,結果將出現在dataviewgrid中。 這是我一直在努力的代碼,問題是什麼都沒有出現,我很確定數據庫中有條目。編輯:這是一個Windows窗體應用程序在C中的SQL搜索查詢#

private void button1_Click(object sender, EventArgs e) 
    { 
     conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI"); 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE @choice = @input", conn); 
     cmd.Parameters.AddWithValue("@choice", comboBox1.Text); 
     cmd.Parameters.AddWithValue("@input", textBox1.Text); 
     ds = new DataSet(); 
     da = new SqlDataAdapter(cmd); 
     da.Fill(ds); 
     dataGridView1.DataSource = ds.Tables[0]; 
     conn.Close(); 
    } 
+0

是否'Tclients'表包含'選擇'專欄?你要過濾哪一列? – 2014-09-13 18:31:37

+1

您不能使用參數來表示列名或表名。 – Steve 2014-09-13 18:32:15

+0

我不知道你不能這樣做,好吧。 – 2014-09-13 18:37:01

回答

3

後添加此不能使用參數來表達一個列的名稱。 你應該列名填充您的組合框及其DropDownStyle屬性設置爲DropDownList(不要讓你的用戶鍵入列的名稱),然後構建查詢

private void button1_Click(object sender, EventArgs e) 
{ 
    string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = @input"; 
    using(SqlConnection conn = new SqlConnection(....)) 
    using(SqlCommand cmd = new SqlCommand(cmdText, conn)) 
    { 
     conn.Open(); 
     cmd.Parameters.AddWithValue("@input", textBox1.Text); 
     ds = new DataSet(); 
     da = new SqlDataAdapter(cmd); 
     da.Fill(ds); 
     dataGridView1.DataSource = ds.Tables[0]; 
    } 
} 
+0

我認爲這是開放的Sql注入!只需寫列名! – mybirthname 2014-09-13 18:39:24

+0

我已經指定列名稱應該被添加到組合框中,並且DropDownStyle應該被設置爲DropDownList。無法編輯此風格 – Steve 2014-09-13 18:41:17

+0

這工作,因爲我希望它是,非常感謝你的幫助 – 2014-09-13 18:51:24

0

你忘了綁定數據源的網格視圖 數據源

dataGridView1.DataSource = ds.Tables[0]; 
dataGridView1.DataBind(); 
+1

DataGridView(或更好的WinForm應用程序)不需要DataBind調用 – Steve 2014-09-13 18:33:12

+0

它添加dataGridView1.DataBind()後給我一個錯誤; – 2014-09-13 18:35:01

+0

你能確認它的ASP.NET應用程序嗎? msg的錯誤是什麼? – chrana 2014-09-13 18:35:57