根据数据库中的值选中单选按钮

时间:2014-01-18 07:35:06

标签: c# oledb

通过此代码,我将以编辑形式从数据库中检索值:

OleDbCommand Comm1 = new OleDbCommand("select image1,image2,image3,image4,measurement,property_purpose,bedrooms,bathrooms,furnishing,property_price,property_price_per_mu,existing_customer from  tb_property where property_id = ?", con);
Comm1.Parameters.AddWithValue("property_id", txt_prop_id.Text);
OleDbDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
       {
          txt_image1.Text = DR1.GetValue(0).ToString();
          txt_image2.Text = DR1.GetValue(1).ToString();
          txt_image3.Text = DR1.GetValue(2).ToString();
          txt_image4.Text = DR1.GetValue(3).ToString();
          combo_measure.Text = DR1.GetValue(4).ToString();
          combo_purpose.Text = DR1.GetValue(5).ToString();

          combo_bedrooms.Text = DR1.GetValue(6).ToString();
          combo_bathrooms.Text = DR1.GetValue(7).ToString();
          combo_furnishing.Text = DR1.GetValue(8).ToString();
          txt_price.Text = DR1.GetValue(9).ToString();
          txt_price_per_mu.Text = DR1.GetValue(10).ToString();
          var val = DR1.GetValue(11).ToString();
          if (val == "Yes")
          {
              radioButton1.Checked;
          }
          if (val == "No")
          {
              radioButton2.Checked;
          }
       }

现在,如果数据库中的radiobuttonsval,那么Yes时遇到问题,那么应该检查radiobutton1

如果No在数据库中,则应选择radiobutton2。但语法显示错误,有人可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

设置单选按钮的已检查属性的语法是

radioButton1.Checked = true;

所以你的代码看起来像

          if (val == "Yes")
          {
              radioButton1.Checked=true;
              radioButton2.Checked=false;
          }
          else if (val == "No")
          {
              radioButton2.Checked=true;
              radioButton1.Checked=false;
          }

答案 1 :(得分:1)

只需更新radiobuttons的Checked属性:

  radioButton1.Checked = (val == "Yes);
  radioButton2.Checked = !radioButton1.Checked;

答案 2 :(得分:0)

Nitin Varpe的答案很棒,但我还有一件事要改进你的代码,那就是用它来索引列

将此代码放在课堂上:

public static class DataExtensions
    {
    public static string GetSafeString(this OleDbDataReader reader, string colName)
    {

        if (reader[colName] != DBNull.Value)
            return reader[colName].ToString();
        else
            return string.Empty;
    }
}

因此,当您呼叫价值时,它将如下所示:

con.Open();
OleDbDataReader DR1 = Comm1.ExecuteReader();

if (DR1.Read())
{

   textBox1.Text = (DataExtensions.GetSafeString(DR1, "COLUMN"));
   var val = (DataExtensions.GetSafeString(DR1, "COLUMN"));

   if (val == "Yes")
   {
       radioButton1.Checked;
   }
   if (val == "No")
   {
       radioButton2.Checked;
   }
}

con.Close();

在更改表结构时,索引列可能会导致整个代码混乱。 希望它有所帮助。