2011-06-27 44 views
0
<asp:TemplateField HeaderText="Select One"> 

    <ItemTemplate> 

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

    </ItemTemplate> 

    </asp:TemplateField> 

在GridView的單選按鈕的使用aspx.cs問題與ASP.NET

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

} 

我無法得到它在RadioButton選擇的行。你能幫我解決這個問題嗎?

+0

只需在將runat = server添加到輸入控件後進行檢查 – V4Vendetta

回答

1

您只能使用FindControl與服務器端控件。與ASP.NET單選按鈕替換您<input> HTML元素,如:

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

,你必須使用runat="server"

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

如前所述,加RUNAT =「服務器」,改變的評估條件的順序從if (rad.Checked&&rad!=null)if (rad!=null && rad.Checked)

順便說一句,在GridView列中排除單選按鈕並不容易。看看這個鏈接,如果你會偶然發現問題:Adding a GridView Column of Radio Buttons