简体   繁体   中英

Problem with usage of RadioButton in GridView in ASP.NET

    <asp:TemplateField HeaderText="Select One">

    <ItemTemplate>

    <input name="MyRadioButton" type="radio" />

    </ItemTemplate>

    </asp:TemplateField> 

aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridViewRow di in GridView1.Rows)
    {
        RadioButton rad = (RadioButton)di.FindControl("MyRadioButton");
        //Giving Error:Object reference not set to an instance of an object.
        if (rad.Checked&&rad!=null)
        {
            s = di.Cells[1].Text;
        }

    }

    Response.Redirect("applicants.aspx?form=" +s);

}

I couldn't get the row which is selected in RadioButton . Can you help me with this please.

You can only use FindControl with server-side controls. Replace your <input> HTML element with an ASP.NET radio button, eg:

<asp:RadioButton ID="MyRadioButton" runat="server"  ... />

你必须使用runat="server"

<input name="MyRadioButton" type="radio" runat="server" id="MyRadioButton" />

As already mentioned, add runat="server" and change order of conditions evaluated from if (rad.Checked&&rad!=null) to if (rad!=null && rad.Checked)

By the way it's not so easy to make radiobuttons in GridView column exclusive. Look at this link if you will stumble on problem: Adding a GridView Column of Radio Buttons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM