I have a list box on my WinForms application which populates with the following SQL code in C#:
private void PopulateClients()
{
string sqlText = "SELECT ClientID, ClientName FROM tblClients;";
cSqlQuery cS = new cSqlQuery(sqlText, "table");
lbxClient.DataSource = cS.cTableResults;
lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";
}
So whilst the list box displays client names, the value it should return when selected is the numerical clientID.
However, later in the code –
private void btnAddNewJob_Click(object sender, EventArgs e)
{
try
{
string strNewJobName = txtNewJobName.Text;
string strNewJobRef = txtNewJobRef.Text;
int intNewJobClient = (int)lbxClient.SelectedValue;
string sqlText = "INSERT INTO tblJobs (JobID, JobClient, JobRef, JobName) " +
"VALUES (@JobID, @JobClient, @JobRef, @JobName);";
SqlCommand sqlCom = new SqlCommand(sqlText);
sqlCom.Parameters.Add("@JobID", SqlDbType.Int);
sqlCom.Parameters.Add("@JobClient", SqlDbType.Int);
sqlCom.Parameters.Add("@JobRef", SqlDbType.Text);
sqlCom.Parameters.Add("@JobName", SqlDbType.Text);
cConnectionString cS = new cConnectionString();
sqlCom.Parameters["@JobID"].Value = cS.NextID("JobID", "tblJobs");
sqlCom.Parameters["@JobClient"].Value = intNewJobClient;
sqlCom.Parameters["@JobRef"].Value = strNewJobRef;
sqlCom.Parameters["@JobName"].Value = strNewJobName;
cSqlQuery cQ = new cSqlQuery(sqlCom, "non query");
PopulateJobs();
txtNewJobName.Text = "";
txtNewJobRef.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Fails on the third line
int intNewJobClient = (int)lbxClient.SelectedValue;
With an invalid cast. As far as I can see the listbox is still returning the Client Name, whereas it should be returning then numerical clientID (int).
Any ideas?
In the end I had to do this:
Which I feel like is a bit of a fudge – but it works!