简体   繁体   中英

Listbox Selected Value Issue

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?

Your code should work - just tested that. Make sure that the data you are binding to is correct - especially ClientID also make sure that the value is selected before casting to int

Hope it helps

lbxClient.SelectedValue is a string. It should be converted to an int like so:

int intNewJobClient = Convert.ToInt32(lbxClient.SelectedValue);

Hope this helps.

I had the same problem but its resolved now by doing this

Replace this

lbxClient.DataSource = cS.cTableResults;
lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";

With

lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";
lbxClient.DataSource = cS.cTableResults;

Just place the first line "DataSource=" in last and the you will get rid out of it :)

The reason is doing this explained in @Sebastian answer.

In the end I had to do this:

int intClient = 0;
        try
        {
            intClient = (int)lbxClient.SelectedValue;
        }
        catch (Exception)
        {
            intClient = 0;
        }

Which I feel like is a bit of a fudge - but it works!

You code should work, However you should place a sanity check on the SelectedValue on the index.

if (lbxClient.SelectedIndex != -1)
{
  int intClient = 0;
  try
  {
     intClient = Convert.ToInt32(lbxClient.SelectedValue);
  }
  catch (Exception)
  {
      // catch if the value isn't integer.
      intClient = -1;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM