Getting text from selected item in RadioButtonList in GridView in ASP.NET
I am trying to extract the id from the gridview row but I keep getting the error:
System.FormatException: Input string was not in a correct format'.
Snippet of code:
foreach (GridViewRow gvrow in GridView1.Rows)
{
RadioButtonList rblAnswer = (RadioButtonList)gvrow.FindControl("rblResult");
string strAnswer = rblAnswer.SelectedValue;
int intAnswer = Convert.ToInt32(strAnswer); //error with this line
Label lblQuestionID = (Label)gvrow.FindControl("lblID");
string strID = lblQuestionID.Text;
int intID = Convert.ToInt32(strID);
Package.Sql.Sql.saveAnswers(Convert.ToInt32(Session["userID"]), intID,
intAnswer);
}
ASP.NET snippet:
<asp:RadioButtonList ID="rblResult" runat="server" Width="200px">
<asp:ListItem Value="1">Strongly Disagree</asp:ListItem>
<asp:ListItem Value="2">Disagree</asp:ListItem>
<asp:ListItem Value="3">Tend to Disagree</asp:ListItem>
<asp:ListItem Value="4">Tend to Agree</asp:ListItem>
<asp:ListItem Value="5">Agree</asp:ListItem>
<asp:ListItem Value="6">Strongly Agree</asp:ListItem>
</asp:RadioButtonList>
+2
source to share
5 answers
FindControl returns a null reference if the specified control does not exist.
foreach (GridViewRow gvrow in GridView1.Rows)
{
RadioButtonList rblAnswer = (RadioButtonList)gvrow.FindControl("rblResult");
...
}
If GridView1 contains any rows that don't contain a control named rblResult, then rblAnswer will be null, so you need to check that rblAnswer is not null before using it.
If the value was not selected from the RadioButtonList, then SelectedValue will return an empty string. So once you find the rblResult control, you need to check if the value is actually selected.
if(rblAnswer != null)
{
if(rblAnswer.SelectedValue != string.Empty)
{
string strAnswer = rblAnswer.SelectedValue;
....
}
}
0