I have a combo box and a checkListbox in my windows form application. In my combo box, I mapped my items to my sql table using this query and displayed it to the my combo box
select * from job_table
SQL table
job_detail
--------------------
jobId | jobName
-------------------
1 | McDonald
2 | Buger King
3 | Security Officer
4 | IT Manager
5 | Teacher
code:
string query = "select jobId, jobName from job_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select a job -------> " };
dt.Rows.InsertAt(dr, 0);
applicationComboBox.DataSource = dt;
applicationComboBox.ValueMember = "jobId";
applicationComboBox.DisplayMember = "jobName";
After the comboBox binding, I call a method call fill_workerCheckList to display a list of worker who is currently on that job.
-----------------------------
workerId | workerName |
-----------------------------
1 | Amy |
2 | Jim |
3 | Peter |
4 | Pam |
5 | David |
6 | Sara |
7 | Laura |
8 | Bob |
I joined the two tables to get their relationship: 1-N: 1 worker can have many job using this join query:
select * from worker_detail as wd
LEFT JOIN job_detail as jd
ON wd.jobId = jd.jobId
-----------------------------------------
workerId | workerName | jobId
------------------------------------------
1 | Amy | 1
2 | Jim | 1
3 | Peter | 2
4 | Pam | 5
5 | David | 3
6 | Sara | 2
7 | Laura | 4
8 | Bob | 4
To display the workerName to a checkListBox, I was thinking to filter by comboBox.selectedIndex, but this is not a good idea because what happen if 1 job was cut, than all the record will be messed up
This is the query that I thought of using SQL injection
select * from worker_detail as wd
LEFT JOIN job_detail as jd
ON wd.jobId = jd.jobId where wd.jobId = '"+comboBox.SelectedIndex+"'
My original code:
SqlCommand myCommand = new SqlCommand(query, myConn);
SqlDataReader dr = myCommand.ExecuteReader();
comboBox.Items.Clear();
string s = "Select All";
comboBox.Items.Add(s);
while (dr.Read())
{
string workerName = dr.IsDBNull(1) ? string.Empty : dr.GetString(1);
checkListBox.Items.Add(name);
}
You can immediately see the problem here. What if the job somehow get cut? then the jobId is gone and the comboBox index won't work. What I want to know is is there a better way to map by the workerId instead of the index?