-3

如何从下面的代码中获取选定的单选按钮值

protected void Page_Load(object sender, EventArgs e)
{
     string query="select top 0.1 percent Title, Answer1, Answer2, Answer3, Answer4 from [Question] order by newid()" ;
     SqlCommand cmd=new SqlCommand(query,con);
     con.Open();
     SqlDataReader dr=cmd.ExecuteReader();
     if(dr.Read())
     {
         rbList1.Items.Add(dr[0].ToString());
         rbList1.Items.Add(dr[1].ToString());
         rbList1.Items.Add(dr[2].ToString());
         rbList1.Items.Add(dr[3].ToString());
     }
     else
     {
         MessageBox.Show("Some Proble Occure !");
     }
     con.Close();
}
4

2 回答 2

1

试试这些

rbList1.SelectedIndex // Gets the index of the currently selected item

rbList1.SelectedItem // Gets the currently selected item

rbList1.SelectedValue // Gets the value of the currently selected item

于 2013-02-19T14:22:09.300 回答
1

先提几点建议:

  • 不要在每次回发时对RadioButtonListfrom进行数据绑定,请检查属性,否则不会触发事件并且您将无法获得所选项目Page_LoadIsPostBack
  • using-statement 用于任何实现IDisposable,尤其是在 System.Data 命名空间中,以确保所有非托管资源(如连接)都被释放/关闭
  • 使用DbDatareaderlike的适当方法GetIntGetString代替使用ToStringfor all(如果字段为空,也会引发异常)

string query = "select top 0.1 percent Title, Answer1, Answer2, Answer3, Answer4 from [Question] order by newid()";
using (var con = new SqlConnection("YourConnectionString"))
using (var cmd = new SqlCommand(query, con))
{
    con.Open();
    using (var dr = cmd.ExecuteReader())
    {
        if (dr.Read())
        {
             rbList1.Items.Add(dr.GetString(0));
             rbList1.Items.Add(dr.GetString(1));
             rbList1.Items.Add(dr.GetString(2));
             rbList1.Items.Add(dr.GetString(3));
        }
    }
}

对于您的问题:我不知道,因为您没有提到实际问题。

如何从下面的代码中获取选定的单选按钮值

然后处理RadioButtonList's SelectedIndexChanged-event

于 2013-02-19T14:23:36.137 回答