2016-01-22 38 views
0

當我PatientId它工作正常更換EmerPacienti,爲什麼發生?無效的列名工作正常

if (DropDownList3.SelectedItem.Value == "In-Pacient") 
{ 
    SqlDataAdapter Da = new SqlDataAdapter("select * from Ipacient where EmerPacienti=" + TextBox11.Text + "", cn); 
    //SqlCommandBuilder Cmd = new SqlCommandBuilder(Da); 
    DataSet Ds = new DataSet(); 
    Da.Fill(Ds, "Ipacient"); 
    GridView1.DataSource = Ds.Tables[0]; 
    GridView1.DataBind(); 
+0

您應該添加一個qoutes SELECT * FROM Ipacient其中EmerPacienti ='」 + TextBox11.Text +「'」 講究 –

回答

1

使用sql參數來防止sql注入,那麼你也不需要把它包裝在文本列所需的撇號中。因此,這是好多了:

using (var cn = new SqlConnection("insert connection string")) 
using(var da = new SqlDataAdapter("select * from Ipacient where [email protected]", cn)) 
{ 
    da.SelectCommand.Parameters.Add("@EmerPacienti", SqlDbType.VarChar).Value = TextBox11.Text; 
    DataTable table = new DataTable(); 
    da.Fill(table); 
    GridView1.DataSource = table; 
    GridView1.DataBind(); 
} 

如果它是一個int - 值使用int.Parse/int.TryParse

using (var cn = new SqlConnection("insert connection string")) 
using(var da = new SqlDataAdapter("select * from Ipacient where [email protected]", cn)) 
{ 
    int patientId; 
    if (int.TryParse(TextBox11.Text, out patientId)) 
    { 
     da.SelectCommand.Parameters.Add("@PatientId", SqlDbType.Int).Value = patientId; 
     // ... 
    } 
} 
+0

謝謝您對雙引號之間的單引號,這是非常有成效的答案:) – Mariohysa