I am working on a windows form application and I have a checkListBox that is binded to my database. I am using parameter method to store the selected Text. However, I want to get the primary key of that item similar to comboBox.SelectedValue
instead of the Text. Are there way to do this?
Here is my code. As you can see, the parameter is filtered by the checkedItem text. When I select my checkedItem from my checkListBox, it suppose to only get the selected items. This work fine if my CheckListBox item has something like Peter, Amy, Bob, and David (non duplicate name). However, if my checkListBox has duplicate name. Peter, Amy, Amy, Bob, David, Amy,this will cause problem. If I select the first Amy, My parameterList
will have Amy, Amy, Amy. This is a problem because I am filtering it by my firstName (so whenever they see the same name, it will add to the parameterList
. What I really want is to filter by a key such as employeeId so that it will not have any duplicate name in my parameterList
. (Just like when I change from comboBox.selecteIndex
to comboBox.selectedValue
). When I selected only the the first Amy, my parameterList should only have one checked Amy, but not all the Amy that isn't even checked. I am wondering if I can do something like selectedValue
from my comboBox value` to map the database value? Help will be appreciated
for example here is my checkListBox:
[x]Amy
[]Peter
[]David
[]Amy
[]Amy
[]Jimmy
You can see only the first Amy is selected. But my parameterList has Amy, Amy, Amy since I am filtering by firstName.
string parameterList = "";
int parameterCounter = 0;
// Add a parameter placeholder for each "checked" item
for (var t = 0; t < employeeCheckListBox.CheckedItems.Count; t++)
{
parameterList += (t == 0) ? "@p" + t : ", @p" + t;
}
string query = "select distinct firstName, lastName, employeeEmail,
entryYear, leaveYear
from[employee_detail] as ed
LEFT JOIN[department_detail] as dd ON ed.employeeId = dd.employeeId
Where firstName = (" + parameterList + ")";
myCommand = new SqlCommand(query, myConn);
for (var t = 0; t < employeeCheckListBox.CheckedItems.Count; t++)
{
myCommand.Parameters.AddWithValue ("@p" + t, employeeCheckListBox.CheckedItems[t].ToString());
}
if (employeeCheckListBox.CheckedItems.Count == 0)
{
myCommand = new SqlCommand(Equery, myConn);
}
Here is what I want to change
string query = "select distinct firstName, lastName, employeeEmail,
entryYear, leaveYear
from[employee_detail] as ed
LEFT JOIN[department_detail] as dd ON ed.employeeId = dd.employeeId
Where firstName = (" + parameterList + ")";
//the parameterList should be the selected value of the checkListBox