显示从数据库中选择的单选按钮 C#

Display a selected radio button from database c#

请问如何根据数据库中的值显示选中的单选按钮?示例:我想显示具有性别值的员工的详细信息(如果员工在数据库中有 "male" 性别,我希望自动选择单选按钮 "Male")

如果您使用的是 WPF,则可以设置代表男性的布尔值 属性。然后绑定到单选按钮的checked属性上。

这样如果男性 属性 returns true ,单选按钮将被选中。

这是一个很好的例子:

Binding radio button

您也可以对这个概念使用依赖性 属性,但我认为第一种方法肯定适合您。

使用 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;}

我有非常简单的方法来将数据库数据显示到此处的表格中。我有学生详细信息数据库,并且在该数据库中我创建了信息 table。我显示信息 table 数据。

 {
            // 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();
        }