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



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

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

   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.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();
   }

已解决!这是我尝试过的,它有效。我希望这对某人有帮助。

  if (txtSearch.Text != "")
        {
            try
            {
                //  open connection
                oCn.Open();
                SqlDataAdapter da = new SqlDataAdapter("sp_offer_search", oCn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.Parameters.Add("@Variable", SqlDbType.VarChar).Value = txtSearch.Text;
                da.SelectCommand.Parameters.Add("@CustomerId", SqlDbType.Int).Value = Session["customerId"];
                da.SelectCommand.Parameters.Add("@Status", SqlDbType.VarChar).Value = "Pending";
                DataTable dt = new DataTable();
                da.Fill(dt);
                GridView1.DataSourceID = String.Empty;
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            catch(Exception ex)
            {
                Response.Write(ex.ToString());
            }
            finally
            {
                oCn.Close();
            }
        }
        else
        {
            GridView1.DataSourceID = "SqlDataSource1";
            SqlDataSource1.SelectCommand = SqlDataSource1.SelectCommand;
            GridView1.DataBind();
        }

最新更新