0

我试图在没有运气的情况下访问网格视图中的控件。我搜索了互联网,没有任何例子可以帮助我。目前,我收到的错误消息是:“对象引用未设置为对象的实例”,指的是这一行: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>
4

2 回答 2

0

看看这个问题的答案:how to access templatefield from code behind . 回答者谈到使用 RowCreated 和 RowDataBound 事件。

于 2012-12-14T20:29:11.313 回答
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;

}
于 2012-12-14T20:52:15.413 回答