Skip to main content
 首页 » 编程设计

c#之使用带参数的存储过程修改 SqlDataSource.SelectCommand

2024年02月06日12kuangbin

我正在尝试在我的应用程序中创建一个搜索框,为此我需要修改 SqlDataSource.SelectCommand。我将不胜感激任何帮助!

为了测试,我是这样做的,它可以工作,但它容易受到 sql 注入(inject)的攻击

   SqlDataSource1.SelectCommand = "sp_offer_search '" + txtSearch.Text + "', " +   Session["customerId"] + " , '" + "Pending"+ "'"; 
   GridView1.DataBind(); 

这是我到目前为止尝试过的方法,但它不起作用:

 if (txtSearch.Text != "") 
        {                 
         //open connection 
          oCn.Open(); 
          SqlCommand com = new SqlCommand(query, oCn); 
          com.CommandType = CommandType.StoredProcedure; 
 
          com.Parameters.AddWithValue("@Variable", txtSearch.Text);   
          com.Parameters.AddWithValue("@CustomerId",Session["customerId"]);    
          com.Parameters.AddWithValue("@Status", txtStatus.Text);    
 
 
            DataTable dt = new DataTable(); 
            dt.Load(com.ExecuteReader()); 
 
            SqlDataSource1.SelectCommand = dt.ToString(); 
            GridView1.DataBind(); 
       } 

请您参考如下方法:

如果 GridView 数据源设置为 SqlDataSource1,则您不需要 DataTable。 DataTable.ToString() 不是 selectCommand。尝试:

 if (txtSearch.Text != "") 
    {                         
      SqlCommand com = new SqlCommand(query, oCn); 
      com.CommandType = CommandType.StoredProcedure; 
 
      com.Parameters.AddWithValue("@Variable", txtSearch.Text);   
      com.Parameters.AddWithValue("@CustomerId",Session["customerId"]);    
      com.Parameters.AddWithValue("@Status", txtStatus.Text);    
 
      SqlDataSource1.SelectCommand = com; 
      GridView1.DataBind(); 
   }