Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

ListBox.SelectedValue not working

Posted on 2008-06-25
23
1,083 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
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
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
 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

808 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