数据库C#中的单选按钮值

本文关键字:单选按钮 数据库 | 更新日期: 2023-09-27 18:00:40

我正试图让我的程序从Access数据库中的特定单元格中读取一个值,以便将该值分配给单选按钮的文本属性。然而,我得到了一个错误,我无法解决问题。这是我的代码:

private void WindowsAnalysisQuiz_Load(object sender, EventArgs e)
{
    //declare connection string using windows security
    string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:''Users''Hannah''Desktop''WindowsAnalysisQuiz.accdb";
   //declare Connection, command and other related objects
   OleDbConnection conGet = new OleDbConnection(cnString);
   OleDbCommand cmdGet = new OleDbCommand();
   try
   {
       //open connection
       conGet.Open();
       cmdGet.CommandType = CommandType.Text;
       cmdGet.Connection = conGet;
       //cmdGet.CommansText = "SELECT 
       cmdGet.CommandText = "SELECT Question FROM WindowsAnalysisQuiz ORDER BY rnd()";
       OleDbDataReader reader = cmdGet.ExecuteReader();
       reader.Read();
       label1.Text = reader["Question"].ToString();
       radioButton.Text = cnString["Quiz"].Rows[0]["Correct Answer"].ToString();
       radioButton1.Text = reader["Answer2"].ToString();
       radioButton2.Text = reader["Answer3"].ToString();
       radioButton3.Text = reader["Answer4"].ToString();
       conGet.Close();
   }
}

我遇到了以radioButton.Text开头的行的问题。显然它有一些无效的参数,参数1无法从字符串转换为int

数据库C#中的单选按钮值

当您可能真的想要一个RadioButtonList时,您似乎正在使用几个不同的RadioButton。

如果你有一个RadioButtonList,那么很容易将一些东西绑定到它,本质上是创建一个列表(从你的数据库或其他什么),然后将其绑定到单选按钮列表。。类似的东西

        var de = new List<string>();
        de.Add("1");
        de.Add("2");
        de.Add("3");
        RadioButtonList1.DataSource = de;
        RadioButtonList1.DataBind();

你的代码不应该是这样的吗:

radioButton.Text = reader["Correct Answer"].ToString();

并将您的选择语句更改为:

cmdGet.CommandText = "SELECT Question, [Correct Answer], Answer2, Answer3, Answer4 FROM WindowsAnalysisQuiz ORDER BY rnd()";