2015年12月9日 星期三

Searching in ASP.Net GridView Multiple Parameters

Searching in ASP.Net GridView Multiple Parameters

cs
private void BindData()
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "select * from customers where (name like '%' + @name + '%' or @name = '') and (age = @age or @age= 0) and (mobile = @mobile or @mobile= '') and (city = @city or @city= '')";
    SqlCommand cmd = new SqlCommand(query);
    cmd.Parameters.AddWithValue("@name", txtName.Text.Trim());
    cmd.Parameters.AddWithValue("@age", txtAge.Text.Trim() == "" ? 0 txtAge.Text.Trim());
    cmd.Parameters.AddWithValue("@mobile", txtMobile.Text.Trim());
    cmd.Parameters.AddWithValue("@city", ddlCity.SelectedIndex > 0 ? ddlCity.SelectedValue : "");
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con; sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }
}



ref url:

沒有留言:

張貼留言