如何获取所选radiobuttonlist项的值

时间:2013-02-19 14:14:38

标签: c# asp.net radiobuttonlist

如何从代码

中获取选定的单选按钮值
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();
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

首先提出一些建议:

  • 不要在每次回发中对RadioButtonList的{​​{1}}进行数据绑定,检查Page_Load属性,否则不会触发事件,也不会获得所选项目
  • IsPostBack - 语句用于实现using的任何内容,尤其是在System.Data命名空间中,以确保处置/关闭所有非托管资源(如连接)
  • 使用IDisposable DbDatareader或[{1}}等GetInt的适当方法,而不是使用GetString(如果字段为空,则会抛出异常)

ToString

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

  

如何从代码

中获取所选的radiobutton值

然后处理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)); } } } 的{​​{3}}。