• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1102
  • Last Modified:

ListBox.SelectedValue not working

Greetings all

I, today, attempted a simple WIndows based application and ran into problems with the "SelectedValue" proeprty of the ListBox (see attached snippet).

In "frmMain_Load" the code executes fine. I copied the same code into "LoadAddresses" and "GetSelectedClientId" and it fails there with "Input string was not in a correct format."

Any ideas?

In advance, thanks!!

  allanmark
public partial class frmMain : Form
    {
        private RealPeople.DataServices GetData;
 
        private DataSet dsAddress;
        private DataSet dsClient;
 
        private DataView dvAddresses;
                         
        //---------------------------------------------------------------------------------------------
        public frmMain()
        {
            InitializeComponent();
            
        }
 
        //---------------------------------------------------------------------------------------------
        private void frmMain_Load(object sender, EventArgs e)
        {
            GetData = new RealPeople.DataServices();
 
            LoadClients();
	 
            // These next 3 statements work fine here.
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string yodd = lblClients.SelectedValue.ToString();
            int iodd = Convert.ToInt32(yodd);
        }
 
        //---------------------------------------------------------------------------------------------
        private void LoadClients()
        {    
            //DataSet dsClient = GetData.GetClients();
            dsClient = GetData.GetClients();
            lblClients.DataSource = dsClient.Tables["Clients"];
            lblClients.DisplayMember = "Client_Name";
            lblClients.ValueMember = "C_Id";            
            
            lblClients.SelectedIndex = 0;
        }
 
        //---------------------------------------------------------------------------------------------
        private void LoadAddresses()
        {
            // These next 3 statements cause a problem here!!
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string yodd = lblClients.SelectedValue.ToString();
            int iodd = Convert.ToInt32(yodd);
 
//            int iClient = GetSelectedClientId();
 
            dsAddress = GetData.GetAddresses();            
 
        }
 
        //---------------------------------------------------------------------------------------------
        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadAddresses();
 
 
        }
 
        //---------------------------------------------------------------------------------------------
        private int GetSelectedClientId()
        {
 
	    // These next 3 statements cause a problem here!!
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string yodd = lblClients.SelectedValue.ToString();
            int iodd = Convert.ToInt32(yodd);
            
	     // These next 2 also cause an error!
            string valueString = lblClients.SelectedValue.ToString();
            int result = Convert.ToInt32(valueString); // TODO: look at Int32.Parse instead of Convert.ToInt32
            return result;
        }
 
        //---------------------------------------------------------------------------------------------
 
       
    }
}

Open in new window

0
allanmark
Asked:
allanmark
  • 14
  • 8
3 Solutions
 
RishadanPortCommented:
Try using listBox.SelectedItem, that's what I always use, and it works
0
 
allanmarkAuthor Commented:
int iNo = Convert.ToInt32(lblClients.SelectedItem.ToString() ); == gives :UInput string was not in the correct format.

All I want out is the value (not the text dispalyed) - this is driving me banannas!! :(  :(  :(

0
 
RishadanPortCommented:
Well... Then simply the input was not in the correct format. Go and debug you could and see what that SelectedItem.ToString()  is.
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
RishadanPortCommented:
obviously, the Convert.ToInt32 method is receiving a bad formatted parameter from the listbox
0
 
RishadanPortCommented:
Check for me if the ListBox's SelectedIndex is not -1 at that line... could maybe be causing problems because of that.
0
 
allanmarkAuthor Commented:
SelectedIndex is 0.

What confuses me is taht the code works in frm_Load.
0
 
anarki_jimbelCommented:
Indeed, RishadanPort is rigth - the best way to figure out what's wrong inyour case is to debug and step through your event handlers.

MSDN documentation for ListBox says, that SelectedValue property gets or sets the value of the member property specified by the ValueMember property. If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object. In othre words, you'll probably get text displayed in the list.

Also, there are many possible reasons why you get an error in the event handler. For example, if at some point (say, e.g., when loading) selected index is '-1' and selected value is nothing - this probably can give this error.



0
 
allanmarkAuthor Commented:
If I look at Load_Clients() -- lblClients.ValueMember = "C_Id" and lblClients.SelectedIndex = 0 --- this causes the SelectedIndexChanged to fire, which calls LoadAddresses() -- where it fails.

If I comment out the code in LoadAddresses, then execution retuirns to frm_Load, when the SAME 3 lines execute ok -- which surely shows that the values are ok??
0
 
RishadanPortCommented:
ya, that's one thing I hate about the selectedIndex changed event. When you change it in your code, it also calls the method.

What I do, when I *do not* want to call the method after changing the selectedIndex, is "lock" the event method using a bool selectedIndexLock.

example:
 
        private bool lockSelectedIndex = false;
        private void LoadClients()
        {    
            //DataSet dsClient = GetData.GetClients();
            dsClient = GetData.GetClients();
            lblClients.DataSource = dsClient.Tables["Clients"];
            lblClients.DisplayMember = "Client_Name";
            lblClients.ValueMember = "C_Id";            
           
            lockSelectedIndex = true;
            lblClients.SelectedIndex = 0;
            lockSelectedIndex = false;
        }

        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!lockSelectedIndex){
               LoadAddresses();
            }
        }

0
 
RishadanPortCommented:
I have had many bugs when I changed the selected Index, and it caused like infinite loops...
0
 
RishadanPortCommented:
I bet you anything that your @ selectedIndex 0, it says something like "Please select something". And then that "please select something" gets sent to the Convert function, which throws an error
0
 
RishadanPortCommented:
I better approach would do this then:

        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!lockSelectedIndex && lblClients.SelectedIndex != 0){
               LoadAddresses();
            }
        }
0
 
allanmarkAuthor Commented:
I did as suggested (see snippet) and it still tried to execute.  Alos, I need to execute  that routine - when the Index is set to 0 (the first entry), the user needs to see the corresponding data.

Me = seriously confused!! :(  :(  :(
    public partial class frmMain : Form
    {
        private RealPeople.DataServices GetData;
 
        private DataSet dsAddress;
        private DataSet dsClient;
 
        private DataView dvAddresses;
 
        private bool lockSelectedIndex = false; 
 
        private void LoadClients()
        {    
            //DataSet dsClient = GetData.GetClients();
            dsClient = GetData.GetClients();
            lblClients.DataSource = dsClient.Tables["Clients"];
            lblClients.DisplayMember = "Client_Name";
            lblClients.ValueMember = "C_Id";
 
            lockSelectedIndex = true;
            lblClients.SelectedIndex = 0;
            lockSelectedIndex = false;
 
        }
 
        private void LoadAddresses()
        {
            int ttt = lblClients.SelectedIndex;
            int tye = Convert.ToInt32(textBox1.Text);
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string yodd = lblClients.SelectedValue.ToString();
            int iodd = Convert.ToInt32(yodd);
 
            int iClient = GetSelectedClientId();
 
            dsAddress = GetData.GetAddresses();            
 
        }
 
 
        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockSelectedIndex)
              LoadAddresses();
 
 
        }

Open in new window

0
 
RishadanPortCommented:
I need to understand what actually is in your ListBox

Can you please like tell us what is in it?

Thanks
0
 
allanmarkAuthor Commented:
In the selectbox is a name (eg. "Jones, Peter") and teh ValueMemebr conatisn the corresponding id (eg. 2).

As an experiment, I commented out the "SelectedIndex_Changed" event and manually called the LoadAdresses after LoadClients was done  --- it works! So "SelectedIndex_Changed" is causing the problem and I'm not sur ehow to get around it -- I need to Load the addresses each time the user moves to another name in the listbox.
0
 
RishadanPortCommented:
As I asked earlier, could you, type out, the list of the listbox data... ie like this
<item1>
<item2>
..
..

I can't really help you unless I have an understand of what is going on...
0
 
allanmarkAuthor Commented:
Tks 4 your patience :)  :)  :)
Sorry .. wasn;t sure what you wanted.

Here goes ...

<Bathalot, Brian>
<Brown, Andy>
<Jones, Kim>
<Sanderson, Sally>
<Smith, Paul>
<Van Der Merwe, Allan>
<Williams, George>

0
 
RishadanPortCommented:
I am still quite confused where the SelectedValue Property was set for each of these elements
0
 
RishadanPortCommented:
Could you do this:

type out:
<SelectedItem 1's String> <SelectedItem 1's Value>
<SelectedItem 2's String> <SelectedItem 2's Value>
.. .. etc
0
 
RishadanPortCommented:
I am sure you will find your problem when you do this, since that methods problem is from the selectedValue being in bad format
0
 
allanmarkAuthor Commented:
Once again, many thanks for your patience!

On the SelectedValue issue -- my understanding was that when the user selects an entry in the listbox, or the index is set programamtically, the SelectedValue is automatically set. Maybe I'm wrong here .

At Breakpoint5, the SelectItem (sSI)  contains "System.Data.DataRowView".

I sat down this morning and tidied up the code (more meaningful names, etc. Also placed breakpoints all over the show and some code on the lblClients_ValueMemberChanged event.

Point of interest from this:  

1.  The lblClients_SelectedIndexChanged event fires twice!. I thought that perhaps it was triggered by
     default, when I assign the 0 value, so I commented this out. It still fires twice!!
2.  At BREAKPOINT4 the string contains "System.Data.DataRowView"
3.   At BREAKPOINT3 the string contains "System.Data.DataRowView"
4.   At BREAKPOINT4 the string contains "System.Data.DataRowView"
5.  At BREAKPOINT3 the string contains "System.Data.DataRowView"
6.  At BREAKPOINT5 the string contains "4" (correct value)
7.  At BREAKPOINT2 the string contains "4" (correct value)
8.  At BREAKPOINT1 the string contains "4" (correct value)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
 
namespace RealPeopleAddresses
{
 
    public partial class frmMain : Form
    {
        private RealPeople.DataServices GetData;
 
        private DataSet dsAddress;
        private DataSet dsClient;
 
        private DataView dvAddresses;
 
//        private bool lockSelectedIndex = false; 
                         
        //---------------------------------------------------------------------------------------------
        public frmMain()
        {
            InitializeComponent();
            
        }
 
        //---------------------------------------------------------------------------------------------
        private void frmMain_Load(object sender, EventArgs e)
        {
            GetData = new RealPeople.DataServices();
 
            LoadClients();
            
            int iSelectedValue = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string sSelectedValue = lblClients.SelectedValue.ToString();
            int iConverted = Convert.ToInt32(sSelectedValue);
            int tt = 0;                     // BREAKPOINT1
        }
 
        //---------------------------------------------------------------------------------------------
        private void LoadClients()
        {    
            //DataSet dsClient = GetData.GetClients();
            dsClient = GetData.GetClients();
            lblClients.DataSource = dsClient.Tables["Clients"];
            lblClients.DisplayMember = "Client_Name";
            lblClients.ValueMember = "C_Id";
 
            string sSelVal = lblClients.SelectedValue.ToString();
 
            //lblClients.SelectedIndex = 0;
            string sSelVal2 = lblClients.SelectedValue.ToString();
 
            int yyyyy = 0;          // BREAKPOINT2
 
        }
 
        //---------------------------------------------------------------------------------------------
        private void LoadAddresses()
        {
            int iInd = lblClients.SelectedIndex;
 
            string sSelectedValLA = lblClients.SelectedValue.ToString();
 
//            int iClient = GetSelectedClientId();
//            dsAddress = GetData.GetAddresses(1);
 
            int t = 0;      //BREAKPOINT3
 
 
        }
 
        //---------------------------------------------------------------/------------------------------
        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
  //          if (!lockSelectedIndex)
            string sSelectedValSI = lblClients.SelectedValue.ToString();
            LoadAddresses();        // BREAKPOINT4
        }
 
        //---------------------------------------------------------------------------------------------
        //private void PopulateAddresses()
        //{
        //    dvAddresses = new DataView(dsAddress.Tables["Addresses"]);
        //    dvAddresses.Sort = "R_Name, A_AddressLine1";
        //    dvAddresses.RowFilter = "A_ClientId = " + lblClients.ValueMember.ToString();
        //    dgvAddress.DataSource = dvAddresses;
 
        //    //gvAnnualLeave.DataBind();
        //}
 
        //---------------------------------------------------------------------------------------------
        private int GetSelectedClientId()
        {           
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            string yodd = lblClients.SelectedValue.ToString();
            int iodd = Convert.ToInt32(yodd);
            
            string valueString = lblClients.SelectedValue.ToString();
            int result = Convert.ToInt32(valueString); // TODO: look at Int32.Parse instead of Convert.ToInt32
            return result;
        }
 
        private void btnInsert_Click(object sender, EventArgs e)
        {
            Form frmDataWork = new frmDataWork();
            frmDataWork.Show();
        }
 
        
 
        //---------------------------------------------------------------------------------------------
private void lblClients_ValueMemberChanged(object sender, EventArgs e)
        {
         string sSI = lblClients.SelectedItem.ToString();
            string tttt = lblClients.SelectedValue.ToString(); ;
            int rrr = Convert.ToInt32(lblClients.SelectedValue.ToString());
            int t = 0;      // BREAKPOINT 5
        }
 
 
       
    }
}

Open in new window

0
 
RishadanPortCommented:
Why is "4" the correct selected value? I thought you said that the listbox contains:
<Bathalot, Brian>
<Brown, Andy>
<Jones, Kim>
<Sanderson, Sally>
<Smith, Paul>
<Van Der Merwe, Allan>
<Williams, George>
0
 
allanmarkAuthor Commented:
The 4 is the value stored in C_Id (the field asssigned to the ValueMember). It passed to a service that retrieves a dataset for that particular client.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 14
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now