我试图在gridview中访问控件而没有运气。我搜索过互联网,没有任何例子可以帮助我。目前,我得到的错误消息是:“对象引用未设置为对象的实例”引用此行:lblErrors.Text = level.SelectedValue;
这是我背后的代码:
protected void setRecruitmentSchoolLevel(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView recruitment = (GridView)sender;
DropDownList level = (DropDownList)e.Row.FindControl("lstLevel");
lblErrors.Text = level.SelectedValue;
}
}
这是我的网站代码:
<asp:GridView ID="gridRecruitment" runat="server" DataSourceID="sourceRecruitment" Width="100%"
CellPadding="4" EnableModelValidation="True" ForeColor="#333333" OnRowDataBound="setRecruitmentSchoolLevel"
GridLines="None" AutoGenerateColumns="False" AllowSorting="true" DataKeyNames="ID" EmptyDataText="No Recruitments">
<Columns>
<asp:HyperLinkField HeaderText="ID" DataTextField="ID" DataNavigateUrlFormatString="~/Admin/Recruit/recruit.aspx?ID={0}" DataNavigateURLFields="ID" Target="_blank" SortExpression="ID"/>
<asp:BoundField HeaderText="Class" DataField="GraduationYear" SortExpression="GraduationYear"/>
<asp:TemplateField HeaderText="Level" SortExpression="LevelName">
<ItemTemplate><%#Eval("LevelName") %></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstLevel" runat="server" DataSourceID="sourceLevels" DataTextField="Abbreviation" DataValueField="ID" SelectedValue='<%#Bind("Level") %>'/>
<asp:SqlDataSource ID="sourceLevels" runat="server" ConnectionString="<%$ ConnectionStrings:DBCS %>" SelectCommand="SELECT Abbreviation, ID FROM Levels WHERE Recruiting = 'True' ORDER BY [Order] DESC"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Commands" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
答案 0 :(得分:0)
看看这个问题的答案:how to access templatefield from code behind。回答者讨论了使用RowCreated和RowDataBound事件。
答案 1 :(得分:0)
我认为你可以尝试这样的事情
protected void gridRecruitment_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView recruitment = (GridView)sender;
GridViewRow row= recruitment.Rows[e.NewEditIndex];
DropDownList level = (DropDownList)row.FindControl("lstLevel");
lblErrors.Text = level.SelectedValue;
}