tags:

views:

101

answers:

2

Make a WinForms application in Visual Studio 2010, .NET 4.0, then make a user control (from Project/Add User Control...) with this code:

public partial class UserControl1 : UserControl
{
    private string _SelectedTable;

    public string SelectedTable
    {
        get { return _SelectedTable; }
        set { _SelectedTable = value; }
    }

    public UserControl1()
    {
        InitializeComponent();
        DataBindings.Add("SelectedTable", listBox1, "SelectedValue");
        listBox1.DataSource = new List<string>();
    }
}

Compile, add the control from the tool box to Form1, compile again and try to close. It won't (right?). Why?

There are things I can do to prevent this from happening, like changing the line DataBindings.Add("SelectedTable", listBox1, "SelectedValue"); to DataBindings.Add("SelectedTable", tablesListBox, "SelectedValue", false, DataSourceUpdateMode.Never);, or removing any of the two lines after InitializeComponent(). But I would like to know why is this happening, or at least, what is in general what I'm doing wrong, the general rule I'm breaking so I don't make a similar mistake again.

+1  A: 

I think it should be couse you never said what SelectedValue is bound to...
I changed your code like so and it works:


Collection<Person> mylist = new Collection<Person>();            
listBox1.DataSource = mylist;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "ID";

DataBindings.Add("SelectedTable", listBox1, "SelectedValue");
Dr TJ
+1  A: 

Apparently it's some kind of validation issue... If you set CausesValidation to false on the user control, it works fine. Not sure what's going on exactly, though...

Anyway, if you're not explicitly setting the ValueMember property, the SelectedValue isn't meaningful, you should use SelectedItem instead. I tried your code with SelectedItem instead of SelectedValue, and it works fine.

Thomas Levesque
Well, `SelectedValue.ToString()` gives me whatever text is selected in the list, same as `SelectedItem.ToString()`. I guess I'll use `SelectedItem` though since it seems to be the convention.
jsoldi
I agree that it *should* work with `SelectedValue` but apparently it doesn't... Perhaps you should file a bug on Microsoft Connect, because I don't see any logical explanation for this behavior.
Thomas Levesque
Actually, it has to be a bug since as you say there is no logical connection, nothing throws an exception and there is no __'Note'__ in Microsoft's documentation.
jsoldi