【发布时间】:2015-06-11 03:44:48
【问题描述】:
请问如何根据数据库中的值显示选定的单选按钮?示例:我想显示具有性别值的员工的详细信息(如果员工在数据库中具有“男性”性别,我希望自动选择单选按钮“男性”)
【问题讨论】:
标签: c# .net c#-4.0 radio-button
请问如何根据数据库中的值显示选定的单选按钮?示例:我想显示具有性别值的员工的详细信息(如果员工在数据库中具有“男性”性别,我希望自动选择单选按钮“男性”)
【问题讨论】:
标签: c# .net c#-4.0 radio-button
如果您使用的是 WPF,则可以设置一个表示男性性别的布尔属性。然后将其绑定到单选按钮的选中属性。
这样如果男性性别属性返回 true ,就会选中单选按钮。
这是一个很好的例子:
您也可以对这个概念使用依赖属性,但我认为第一种方法肯定适合您。
【讨论】:
使用BindingSource:
BindingSource myBindingSource = new BindingSource();
bindingSource.DataSource = (your datasource here, could be a DataSet or an object)
var maleBinding = new Binding("Checked", myBindingSource , "Gender");
maleBinding.Format += (s, args) => args.Value = ((string)args.Value) == "Male";
maleBinding.Parse += (s, args) => args.Value = (bool)args.Value ? "Male" : "Female";
maleRadioButton.DataBindings.Add(maleBinding);
var femaleBinding = new Binding("Checked", myBindingSource , "Gender");
femaleBinding.Format += (s, args) => args.Value = ((string)args.Value) == "Female";
femaleBinding.Parse += (s, args) => args.Value = (bool)args.Value ? "Female" : "Male";
femaleRadioButton.DataBindings.Add(femaleBinding);
取自here
【讨论】:
它对我来说很成功,我只是使用 datagridview 来比较数据库中的值和单选按钮的值。
GridView grid = new GridView();
grid.ShowDialog();
if (grid.dataGridView1.CurrentRow.Cells[3].Value.ToString()=="Male")
{male_radiobtn.Checked=true;
female_radiobtn.Checked=false;}
else {female_radiobtn.Checked=true;
male_radiobtn.Checked=false;}
【讨论】:
我有一个非常简单的方法可以在这里将数据库数据显示到表单中。我有学生详细信息数据库,在这个数据库中我创建了信息表。然后显示信息表数据。
{
// this code is to display data from the database table to application
int stdid = Convert.ToInt32(txtId.Text); // convert in to integer to called in sqlcmd
SqlConnection con = new SqlConnection("Data Source=MILK-THINK\\SQLEXPRESS;Initial Catalog=Student Details;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select *from info where Student_id=" + stdid,con); // pass the query with connection
SqlDataReader dr; // this will read the data from database
dr = cmd.ExecuteReader();
if(dr.Read()==true)
{
txtName.Text = dr[1].ToString(); // dr[1] is a colum name which goes in textbox
cmbCountry.SelectedItem = dr[2].ToString(); // combobox selecteditem will be display
// for radio button we have to follow this method which in nested if statment
if(dr[3].ToString()=="Male")
{
rdbMale.Checked=true;
}
else if (dr[3].ToString() == "Female")
{
rdbFemale.Checked = true;
}
else
{
MessageBox.Show("There are no records");
dr.Close();
}
}
con.Close();
}
【讨论】: