我試圖在沒有運氣的情況下訪問gridview中的控件。我搜索了互聯網,沒有任何例子能夠幫助我。目前,我收到的錯誤消息是:「對象引用未設置爲對象的實例」引用此行:lblErrors.Text = level.SelectedValue;在gridview中訪問控制
這裏是後面的我的代碼:
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>
我懷疑你可以在你的onrowdatabound事件訪問編輯模板。如果我沒有記錯,編輯模板根本不會被渲染,直到您真正開始編輯該行。 –
謝謝。我必須使用RowEditing事件嗎? – cunjiva
值得一試。我手邊沒有VS,無法檢查。 –