在Gridview中显示SQL Server数据库值,显示错误

时间:2014-10-08 14:36:23

标签: c# sql sql-server gridview

当我尝试在gridview中显示数据库值时,出现错误:

  

System.Data.dll中出现未处理的“System.Data.SqlClient.SqlException”类型异常

     

其他信息:关键字'和'附近的语法不正确。

代码是

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];
}

2 个答案:

答案 0 :(得分:1)

使用可能解决此问题的sql-parameters并防止将来出现sql注入问题:

string sql = @"
SELECT roll_num, 
       mark 
FROM   marks 
WHERE  mark < 50 
AND    dept_id=@dept_id
AND    sem_id=@sem_id 
AND    subject_id=@subject_id 
AND    batch_id=@batch_id 
AND    cls_id=@cls_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,您应该相应地解析它们(int.Parse(home.cboxdept.SelectedValue ))。

答案 1 :(得分:0)

此处缺少使用databind方法。使用以下代码:

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

`