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


After looking at your ASPX code there is a way to get the text. I haven't tested this, but something along these lines should work:



string strAnswer = String.Empty;
foreach (ListItem item in rblAnswer.Items)
{
    if (item.Selected) 
    {
         strAnswer = item.Value;
    }
}

      

+4


source


What is the meaning of rblAnswer.SelectedValue? if it cannot be converted to Int32 .. you will get this error



So it must be Integer

0


source


The only thing you need to know is the value coming from this line of code:

strAnswer = rblAnswer.SelectedValue;

      

Is this a valid integer that can be converted or not?

0


source


Try using tryparse

int.tryparse (strAnswer, out intAnswer);

this will return false if the string cannot be converted.

0


source


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


source







All Articles