SEARCH SELECTED CHECKBOX VALUES

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C# 
C#
 971  View(s)
Ratings:
Rate this:

I have a dropdown with checkbox list. When I select items and try to display in the grid by clicking the search button, I'm not able to do that.

protected void btnSearchEmpCode_Click(object sender, EventArgs e)

    {

        string selectedValues = string.Empty;

        foreach (ListItem item in cblEmpCode.Items)

        {

            if (item.Selected)

                selectedValues += "'" + item.Value + "',";

        }

        if (selectedValues != string.Empty)

            selectedValues = selectedValues.Remove(selectedValues.Length - 1);

        SqlConnection con = new SqlConnection(strcon);

        SqlCommand cmd = new SqlCommand("SELECT *FROM Details WHERE Emp_Code IN (" + selectedValues + ")", con);

        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        Adpt.Fill(dt);

        AIGrids.DataSource = dt;

        AIGrids.DataBind();

    }

Can anyone correct me if I have went wrong somewhere.

  1. ezra heywood

    Post:145

    Points:1019
    Re: Search selected checkbox values

    Hi Chintoo,

    Problem 1: you are adding single quotes ' to Emp_Code column .

    Problem 2: you are not giving space between * and FROM

    Try This:

    protected void btnSearchEmpCode_Click(object sender, EventArgs e)

    {

        string selectedValues = string.Empty;

        foreach (ListItem item in cblEmpCode.Items)

        {

            if (item.Selected)

                selectedValues +=  item.Value + ",";

        }

     

        if (selectedValues != string.Empty)

            selectedValues = selectedValues.Remove(selectedValues.Length - 1);

        SqlConnection con = new SqlConnection(strcon);

        SqlCommand cmd = new SqlCommand("SELECT * FROM Details WHERE Emp_Code IN (" + selectedValues + ")", con);

        SqlDataAdapter Adpt = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        Adpt.Fill(dt);

        AIGrids.DataSource = dt;

        AIGrids.DataBind();

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!