asp.net SqlDataSource 预编译 动态SQL搜索

yzmm
635 阅读
配置SqlDataSource1,搜索的一般需要动态查询,为了解决拼SQL问题,可以采用预编译。参考:SqlDataSource 中 参数动态赋值的方法 和 使用 SqlDataSource 进行带参数的查询
protected void Button1_Click(object sender, EventArgs e)
    {
        string id = TextBox1.Text.ToString();
        string orgName = TextBox2.Text.ToString();
        this.SqlDataSource1.SelectParameters.Clear();
        string sql = "SELECT * FROM sys_user WHERE 1 = 1 ";
        if(id!=null && !"".Equals(id)){
            sql += " and id= @id ";
            this.SqlDataSource1.SelectParameters.Add("id", System.TypeCode.Object, id);
        }
        if (orgName != null && !"".Equals(orgName))
        {
            sql += " and org_name like '%' + @orgName + '%' ";
            this.SqlDataSource1.SelectParameters.Add("orgName", System.TypeCode.String, orgName);
        }
        SqlDataSource1.SelectCommand = sql;
        this.SqlDataSource1.DataBind();
        this.GridView1.DataBind();
    }

评论 (0)

发表评论