Binding textboxes to properties of a comboBox.SelectedItem

后端 未结 2 490
感动是毒
感动是毒 2021-01-27 13:55

I\'m using winforms and I\'ve got a comboBox that represents an IQueryable. Below the combobox is a series of textboxes that I would like to be bound to the currently selected

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-27 14:35

    My original answer was wrong, and admittedly I do not fully understand what all is happening here, but I have a solution which is working.

    Basically you need to grab the BindingManagerBase from the BindingContext and use it to enforce databinding on each SelectedItemChanged event.

    public partial class TestForm : Form
    {
        public DataClassesDataContext DataContext;
    
        public IQueryable datasource;
        private BindingManagerBase bmComboBoxSelectedItem;
    
        // Ctor
        public TestForm()
        {
            InitializeComponent();
    
            // L2S data context
            this.DataContext = new DataClassesDataContext();
    
            // Get the variable for the data source
            this.datasource = this.DataContext.Ts;
    
            // setup the binding for the combobox
            this.comboBox1.DataSource = this.datasource;
            this.comboBox1.DisplayMember = "Description";
            this.comboBox1.ValueMember = "Id";
    
            // assign the databindings of the text boxes to the selectedItem of the combo box    
            // this is where the problem is, afaik
            TId.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.Id"));
            TUser.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.User"));
            TDescription.DataBindings.Add(new Binding("Text", this.comboBox1, "SelectedItem.Description"));
    
            bmComboBoxSelectedItem = this.BindingContext[this.comboBox1, "SelectedItem"];
        }
    
        // make sure you assign this event on the forms designer or your preferred method
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            bmCustomers.ResumeBinding();
        }
    }
    

    This MSDN article helped a lot.

提交回复
热议问题