2014-10-08 102 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))。