ComboBox SelectedValue is null

T

T

m_list.SelectedValue returns null in MainForm.valueChanged regardless
of which value is selected. Is this expected behaviour? SelectedItem
*does* return the correct value.

Code:
using System;
using System.Windows.Forms;

class Attr {	// a simple name value class
string m_name;
string m_value;
public Attr(string name, string value){ m_name = name; m_value =
value; }
public string Name { get { return m_name; } }
public string Value { get { return m_value; } }
}

public class MainForm : Form {
public static void Main(string[] args){
Application.Run(new MainForm());
}

ComboBox m_list;

public MainForm(){
m_list = new ComboBox();
Controls.Add(m_list);
m_list.DisplayMember = "Name";
m_list.ValueMember = "Value";

m_list.Items.Add(new Attr("one", "1"));
m_list.Items.Add(new Attr("two", "2"));
m_list.Items.Add(new Attr("three", "3"));

m_list.SelectedValueChanged += new EventHandler(valueChanged);
}

public void valueChanged(object sender, EventArgs args){
if(m_list.SelectedIndex != -1)
Text = m_list.SelectedValue.ToString();
}
}
 
E

Erick

Please try to change the

Text = m_list.SelectedValue.ToString();

to

Text = m_list.Text;



using System;
using System.Windows.Forms;


class Attr
{ // a simple name value class
string m_name;
string m_value;
public Attr(string name, string value)
{
m_name = name; m_value =
value; }
public string Name { get { return m_name; } }
public string Value { get { return m_value; } }



}


public class MainForm : Form
{
public static void Main(string[] args)
{
Application.Run(new MainForm());
}

ComboBox m_list;


public MainForm()
{
m_list = new ComboBox();
Controls.Add(m_list);
m_list.DisplayMember = "Name";
m_list.ValueMember = "Value";


m_list.Items.Add(new Attr("one", "1"));
m_list.Items.Add(new Attr("two", "2"));
m_list.Items.Add(new Attr("three", "3"));


m_list.SelectedValueChanged += new EventHandler(valueChanged);
}


public void valueChanged(object sender, EventArgs args)
{
if(m_list.SelectedIndex != -1)
Text = m_list.Text;
}


}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top