2014-10-08 145 views
0

當我試圖在GridView中顯示數據庫值我得到一個錯誤:在GridView的顯示SQL Server數據庫中值顯示錯誤

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Incorrect syntax near the keyword 'and'.

而且代碼

private void button1_Click(object sender, EventArgs e) 
{ 
    SqlDataAdapter adap; 
    DataSet ds; 

    SqlConnection cn = new SqlConnection(
     @"Data Source=DILIPWIN\SQLEXPRESS;Initial Catalog=radb;Integrated Security=True"); 
    cn.Open(); 

    var home = new Home(); 
    adap = new SqlDataAdapter(
     "select roll_num, mark from marks where mark < 50 and dept_id=" + 
     home.cboxDept.SelectedValue + " and sem_id=" + home.cboxSem.SelectedValue + 
     " and subject_id=" + home.cboxSubject.SelectedValue + " and batch_id= " + 
     home.cboxBatch.SelectedValue + " and cls_id=" + home.cboxClass.SelectedValue, cn); 

    ds = new System.Data.DataSet(); 
    adap.Fill(ds, "dataGridView1"); 

    dataGridView1.DataSource = ds.Tables[0]; 
} 
+0

你可以發佈後的所有連接查詢? – NMK 2014-10-08 14:43:09

+0

我假設你正在使用__WinForms__,實際上是使用__DataGridView__?請__always標籤適當_否則你浪費__WPF__人們的時間! (反之亦然..) – TaW 2014-10-08 14:50:14

回答

0

使用缺少調用數據綁定方法here.Use以下代碼:

GridView1.DataBind();//This line is missing in your code` 

嘗試下面的格式

DataAdapter adapter=new DataAdapter(SqlCommand,SqlConn); 
DataTable tbl=new Datatable(); 
adapter.Fill(tbl); 
GridView1.DataSource=tbl; 
GridView1.DataBind();//This line is missing in your code 

`

+2

_「關鍵字附近的語法不正確」和「。」_它也是winforms而不是webforms。 – 2014-10-08 14:41:50

1

使用SQL參數這可能解決了這個問題,並防止未來的SQL注入的問題:

string sql = @" 
SELECT roll_num, 
     mark 
FROM marks 
WHERE mark < 50 
AND [email protected]_id 
AND [email protected]_id 
AND [email protected]_id 
AND [email protected]_id 
AND [email protected]_id;"; 

DataSet ds = new DataSet(); 
using(var cn = new SqlConnection(@"Data Source=DILIPWIN\SQLEXPRESS;Initial Catalog=radb;Integrated Security=True")) 
using (var da = new SqlDataAdapter(sql, cn)) 
{ 
    da.SelectCommand.Parameters.AddWithValue("@dept_id", home.cboxDept.SelectedValue); 
    da.SelectCommand.Parameters.AddWithValue("@sem_id", home.cboxSem.SelectedValue); 
    da.SelectCommand.Parameters.AddWithValue("@subject_id", home.cboxSubject.SelectedValue); 
    da.SelectCommand.Parameters.AddWithValue("@batch_id", home.cboxBatch.SelectedValue); 
    da.SelectCommand.Parameters.AddWithValue("@cls_id", home.cboxClass.SelectedValue); 
    da.Fill(ds); // you don't need to open/close the connection with Fill 
} 
dataGridView1.DataSource = ds.Tables[0]; 

你也應該使用正確的類型。 AddWithValue將嘗試從該值推斷出該類型。所以如果這些是int s你應該相應地解析它們(int.Parse(home.cboxdept.SelectedValue))。