Ruchi
Ruchi

Reputation: 146

Csharp : Load Checked Item List based on the Value in Combo Box

I am unable to get the expected results in the below code.

I am trying to select one item from the combo box and I need to get the corresponding values for the the selected item in the Checked List Box. Example is the Manager and Reportees, So if I select one Manager I should see only the list of those employee who are reporting to the Manager that is selected.

enter image description here

My checked List box shows Empty.

My code below which I am raising on the Manager - Selected Item Change Event:

private void Cbreporting_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }

        try
        {
            con.Open();
            string sql1 = "Select distinct empname from tbl_emp_details where isdeleted <>1 and [reporting manager]='@lm'";
            SqlCommand com = new SqlCommand(sql1, con);
            com.Parameters.AddWithValue("@lm", Cbreporting.SelectedIndex);

            SqlCommand cmd1 = new SqlCommand(sql1, con);
            datareader = cmd1.ExecuteReader();
            while (datareader.Read())
            {
                checkedListBox1.Items.Add(datareader[0]);
            }

            con.Close();
            datareader.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error", ex.ToString());
        }

    }

Upvotes: 0

Views: 78

Answers (1)

AJITH
AJITH

Reputation: 1175

I am seeing 2 command objects com and cmd1 and your SqlParameter '@lm' is assigned to com. Bur your 'ExecuteReader' uses the cmd1 object. Modify your code like below.

con.Open();
string sql1 = "Select distinct empname from tbl_emp_details where isdeleted <>1 and [reporting manager]='@lm'";
SqlCommand com = new SqlCommand(sql1, con);
com.Parameters.AddWithValue("@lm", Cbreporting.SelectedIndex);

datareader = com.ExecuteReader();
while (datareader.Read())
{
     checkedListBox1.Items.Add(datareader[0]);
}

con.Close();
datareader.Close();

Upvotes: 1

Related Questions