WinForm binding radio button

前端 未结 3 1831
别那么骄傲
别那么骄傲 2021-02-05 08:42

I use VS2010 and then drag and drop Member datagridview to design view. After that I drag and drop name member textfield to design view and then try to edit and save. It\'s work

3条回答
  •  攒了一身酷
    2021-02-05 09:37

    Here are two possible solutions.


    Binding Format and Parse events

    The Binding class has a built-in facility for on-the-fly transformations of bound data in the form of the Format and Parse events.

    Here's how you would use those events with just the "Male" radiobutton. Create the binding in code, not in the designer:

    // create binding between "Sex" property and RadioButton.Checked property
    var maleBinding = new Binding("Checked", bindingSource1, "Sex");
    // when Formatting (reading from datasource), return true for M, else false
    maleBinding.Format += (s, args) => args.Value = ((string)args.Value) == "M";
    // when Parsing (writing to datasource), return "M" for true, else "F"
    maleBinding.Parse += (s, args) => args.Value = (bool)args.Value ? "M" : "F";
    // add the binding
    maleRb.DataBindings.Add(maleBinding);
    
    // you don't need to bind the Female radiobutton, just make it do the opposite
    // of Male by handling the CheckedChanged event on Male:
    maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;
    

    Computed Property

    Another approach is to add a computed property to your datasource:

    public bool IsMale
    { 
        get { return Sex == "M"; }
        set 
        {  
            if (value)
                Sex = "M";
            else
                Sex = "F";
        }
    }
    

    Now you can simply bind the Male radiobutton to this property on your datasource (just don't show this property in the grid).

    And again you can hook up Female to Male like so:

    maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;
    

提交回复
热议问题