这是我的标记视图
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="SemesterID" DataSourceID="SqlDataSource1" >
<Columns>
<asp:BoundField DataField="SemesterID" HeaderText="SemesterID" InsertVisible="False" ReadOnly="True" SortExpression="SemesterID" />
<asp:BoundField DataField="SemesterName" HeaderText="SemesterName" SortExpression="SemesterName" />
<asp:TemplateField>
<asp:PlaceHolder ID="pHldr" runat="server"></asp:PlaceHolder>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:SqlDataSource ConnectionString="<%$ connectionStrings:MyConnection %>" ID="SqlDataSource1" runat="server" ProviderName="System.Data.SqlClient" SelectCommand="SELECT SemesterID, SemesterName FROM Semesters"></asp:SqlDataSource>
</form>
</body>
这是我的代码behinde文件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < 3; i++)
{
PlaceHolder plHldr = e.Row.FindControl("pHldr") as PlaceHolder;
CheckBox cbx = new CheckBox();
plHldr.Controls.Add(cbx);//Here I get the exception
}
}
我想在PlaceHolder中添加复选框等控件,但我在plHldr.Controls.Add(cbx);
答案 0 :(得分:0)
可能是因为你没有对第一行(行索引-1
)进行处理,这是标题。尝试使用e.Row.RowIndex
确保您没有尝试从标题行转换控件:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0) return;
for (int i = 0; i < 3; i++)
{
PlaceHolder plHldr = e.Row.FindControl("pHldr") as PlaceHolder;
CheckBox cbx = new CheckBox();
plHldr.Controls.Add(cbx);//Here I get the exception
}
}