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

Car*_*los 2 c# sql sql-server sqldatasource

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

为了进行测试,我这样做了,它可以工作,但很容易受到 sql 注入的攻击

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

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

 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();
       }
Run Code Online (Sandbox Code Playgroud)

Cro*_*der 5

如果 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();
   }
Run Code Online (Sandbox Code Playgroud)