First off, make it a habit to put objects that eat resources such as
SqlConnection
,
SqlCommand
and
SqlDataAdapter
within a using statement to ensure that objects will be properly disposed and closed after they are used.
Second, if your
QuestionGrid
is a
GridView
, then you can't just use
FindControl()
method directly to it since a
GridView
is composed of
Rows
and
Columns
. This means that you need to traverse to its rows first before using
FindControl
.
Third, you can't compare the result of FindControl() method to a string. So this line
if (QuestionGrid.FindControl("Option1") == ddt.Rows[0]["Answer"])
of code will fail.
Here's what you can try:
protected void Exambutton_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string sqlStatement = "SELECT Answer FROM [Biology]";
using(SqlConnection connection = new SqlConnection("Your Connection String from your Web.config")){
using(SqlCommand cmd = new SqlCommand(sqlStatement ,connection)){
cmd.CommandType = CommandType.Text;
using(SqlDataAdapter da = new SqlDataAdapter(cmd)){
da.Fill(dt);
if(dt.Rows.Count > 0){
int index = 0;
foreach (GridViewRow row in QuestionGrid.Rows){
RadioButton rb = (RadioButon) row.FindControl("Option1");
if(rb != null){
if(rb.Text == dt.Rows[index]["Answer"]){
rb.Checked = true;
}
}
index++;
}
}
else{
}
}
}
}
}