【问题标题】:Check radio button in RadioButtonList based on text value read from database根据从数据库读取的文本值检查 RadioButtonList 中的单选按钮
【发布时间】:2016-06-17 20:39:50
【问题描述】:

在用户界面中,我有单选按钮列表,其中包含(一级、二级、三级)。另一方面,我有学生表(ID,姓名,级别,DOB,....),它将学生的级别保存为varchar。 在页面加载中,我想根据从数据库读取的值填充 radioButtonList。 以下代码正在运行,但它不检查从 DB 读取它的合适单选按钮。

using (MySqlConnection SqlCon = new MySqlConnection(connStr))
                {
                    MySqlDataReader myReader = null;
                    using (MySqlCommand cmd = new MySqlCommand("SELECT S_Id, level FROM student where S_Id='" + 111 + "'"))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = SqlCon;
                        SqlCon.Open();
                        myReader = cmd.ExecuteReader();
                        if (RadioButtonList1.Items.FindByValue(myReader.ToString()) != null)
                        {
                           // RadioButtonList1.Items.FindByValue(myReader.ToString()).Selected = true;
                            RadioButtonList1.SelectedValue = myReader.ToString();
                        }

                        SqlCon.Close();
                    }
                }

【问题讨论】:

  • 您为从数据库获取数据而调用的代码是否在回发检查中?
  • 是的,我把这段代码放在里面: if (!this.IsPostBack) {...My Code...}
  • radioButtonList1.Items.FindByText("你的文本").Selected = true;或者您也可以使用 Items Index RadioButtonList.Items[1].Selected = true;
  • RadioButtonList1.SelectedValue 很好。您可以发布您的 itemsource 示例吗? myReader.ToString() 是 itemssource 价值的一部分吗?
  • 我需要从代码中:1)从数据库中选择 s_Id=111 的级别。 2) 该级别应由程序检查。例如,第二级的 id=111 的学生 A。程序从 DB 中读取关卡并检查单选按钮列表。

标签: c# mysql asp.net radiobuttonlist


【解决方案1】:

您必须遍历 DataReader 对象才能获取其值。试试这样的:

using (MySqlConnection SqlCon = new MySqlConnection(connStr))
{
   MySqlDataReader myReader = null;
   using (MySqlCommand cmd = new MySqlCommand("SELECT S_Id, level FROM student where S_Id='" + 111 + "'"))
 {
  cmd.CommandType = CommandType.Text;
  cmd.Connection = SqlCon;
  SqlCon.Open();
  myReader = cmd.ExecuteReader();
  while (myReader.Read())
  {
   if (RadioButtonList1.Items.FindByValue(myReader["level"].ToString()) != null)
   {                           
     RadioButtonList1.SelectedValue = myReader["level"].ToString();
   }               
  }
  sqlCon.Close();
 }
}

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 2013-03-19
    • 1970-01-01
    • 2016-12-10
    • 2013-03-25
    • 2016-05-08
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多