John
John

Reputation: 51

Check radio button in RadioButtonList based on text value read from database

In the user interface, i have radio button list which contains (Level One, Level Two, Level Three). On the other hand, I have student table(ID,name,level,DOB,....) which save the the student's level as varchar. In page load, i want to fill the radioButtonList based on the value read from database. the following code is running but it does not check the suitble radio button which read it from 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();
                    }
                }

Upvotes: 0

Views: 1559

Answers (1)

Bharathi
Bharathi

Reputation: 1025

You have to traverse through the DataReader object to get its values. Try something like this:

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();
 }
}

Upvotes: 1

Related Questions