Ato*_*Hic 18 c# data-binding datagridview radio-button winforms
我使用VS2010,然后将Member datagridview拖放到设计视图中.之后,我将名称成员文本字段拖放到设计视图,然后尝试编辑和保存.它运作正常.
然后我拖放性别单选按钮来设计视图.但绑定它不起作用.
我怎么能在这种情况下绑定?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void memberBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.memberBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.dbDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dbDataSet.Member' table. You can move, or remove it, as needed.
this.memberTableAdapter.Fill(this.dbDataSet.Member);
// TODO: This line of code loads data into the 'dbDataSet.Member' table. You can move, or remove it, as needed.
this.memberTableAdapter.Fill(this.dbDataSet.Member);
}
private void memberBindingNavigatorSaveItem_Click_1(object sender, EventArgs e)
{
this.Validate();
this.memberBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.dbDataSet);
}
}
}
Run Code Online (Sandbox Code Playgroud)

Igb*_*man 15
这有两种可能的解决方案.
绑定格式和解析事件
该Binding班有上即时绑定数据的转换的形式内置在设备格式和解析事件.
以下是如何使用"男性"单选按钮进行这些事件.在代码中创建绑定,而不是在设计器中:
// 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;
Run Code Online (Sandbox Code Playgroud)
计算财产
另一种方法是向您的数据源添加计算属性:
public bool IsMale
{
get { return Sex == "M"; }
set
{
if (value)
Sex = "M";
else
Sex = "F";
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您只需将Male radiobutton绑定到数据源上的此属性(只是不要在网格中显示此属性).
你可以再次将女性与男性联系起来:
maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;
Run Code Online (Sandbox Code Playgroud)