2015-04-06 95 views
0

請如何根據數據庫中的值顯示選定的單選按鈕?例如:我想顯示具有性別值的員工的詳細信息(如果員工在數據庫中具有「男性」性別,我希望自動選擇單選按鈕「男性」)顯示從數據庫中選定的單選按鈕c#

回答

0

它的作品成功地對我採取的,我只是用一個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;} 
0

如果您使用的是WPF,你可以設置一個表示男性性別的布爾屬性。然後將其綁定到單選按鈕checked屬性。

這樣,如果男性性別屬性返回true,單選按鈕將被檢查。

這裏是一個很好的例子:

Binding radio button

您還可以使用依賴屬性這一概念,但我認爲第一種方法會爲你工作是肯定的。

+0

感謝,但我使用Windows形成 –

+0

@ leila.net您可以使用下面的鏈接,以雙贏的形式 上使用相同的概念(HTTP [單選按鈕的Windows窗體與INotifyPropertyChanged的結合?]://計算器。 com/questions/5264860/radiobutton-binding-in-windows-forms-with-inotifypropertychanged) – DeJaVo

0

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

+0

請問哪裏可以放這個代碼? –

+0

在表單加載事件中。 –

0

我有很簡單的方法就在這裏顯示的表單的數據庫數據..我有學生詳細信息的數據庫,並在此數據庫中,我創建了信息表。我顯示信息表數據。

{ 
      // 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(); 
     } 
相關問題