Solved

ListBox.SelectedValue not working

Posted on 2008-06-25
23
1,079 Views
Last Modified: 2012-06-22
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
Comment
Question by:allanmark
  • 14
  • 8
23 Comments
 
LVL 6

Accepted Solution

by:
RishadanPort earned 150 total points
ID: 21869551
Try using listBox.SelectedItem, that's what I always use, and it works
0
 

Author Comment

by:allanmark
ID: 21869754
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21869798
Well... Then simply the input was not in the correct format. Go and debug you could and see what that SelectedItem.ToString()  is.
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21869824
obviously, the Convert.ToInt32 method is receiving a bad formatted parameter from the listbox
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21869832
Check for me if the ListBox's SelectedIndex is not -1 at that line... could maybe be causing problems because of that.
0
 

Author Comment

by:allanmark
ID: 21869865
SelectedIndex is 0.

What confuses me is taht the code works in frm_Load.
0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 100 total points
ID: 21869932
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
 

Author Comment

by:allanmark
ID: 21869978
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
 
LVL 6

Assisted Solution

by:RishadanPort
RishadanPort earned 150 total points
ID: 21870005
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870011
I have had many bugs when I changed the selected Index, and it caused like infinite loops...
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870021
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870038
I better approach would do this then:

        private void lblClients_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!lockSelectedIndex && lblClients.SelectedIndex != 0){
               LoadAddresses();
            }
        }
0
 

Author Comment

by:allanmark
ID: 21870066
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870142
I need to understand what actually is in your ListBox

Can you please like tell us what is in it?

Thanks
0
 

Author Comment

by:allanmark
ID: 21870242
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870277
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
 

Author Comment

by:allanmark
ID: 21870312
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870354
I am still quite confused where the SelectedValue Property was set for each of these elements
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870363
Could you do this:

type out:
<SelectedItem 1's String> <SelectedItem 1's Value>
<SelectedItem 2's String> <SelectedItem 2's Value>
.. .. etc
0
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21870377
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
 

Author Comment

by:allanmark
ID: 21872208
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
 
LVL 6

Expert Comment

by:RishadanPort
ID: 21872402
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
 

Author Comment

by:allanmark
ID: 21872454
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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now