Solved

ListBox.SelectedValue not working

Posted on 2008-06-25
23
1,077 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
Comment Utility
Try using listBox.SelectedItem, that's what I always use, and it works
0
 

Author Comment

by:allanmark
Comment Utility
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
Comment Utility
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
Comment Utility
obviously, the Convert.ToInt32 method is receiving a bad formatted parameter from the listbox
0
 
LVL 6

Expert Comment

by:RishadanPort
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I have had many bugs when I changed the selected Index, and it caused like infinite loops...
0
 
LVL 6

Expert Comment

by:RishadanPort
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 6

Expert Comment

by:RishadanPort
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
I am still quite confused where the SelectedValue Property was set for each of these elements
0
 
LVL 6

Expert Comment

by:RishadanPort
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

763 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

9 Experts available now in Live!

Get 1:1 Help Now