我希望 FindControl 从 VB.Net 代码隐藏文件中“查看”ASP.Net DetailsView 中的控件。它没有找到任何一个。
该页面的标记使用 MasterPage。
<%@ Page
Title="Attendance"
Language="vb"
AutoEventWireup="false"
MasterPageFile="~/Knowledge Academy.Master"
CodeBehind="Attendance.aspx.vb"
Inherits="Knowledge_Academy.Attendance" %>
<asp:Content
ID="ContentBody"
ContentPlaceHolderID="BodyPlaceholder"
runat="server">
目前,我们的 DetailsView 的属性如下所示:
<asp:DetailsView
ID="DetailsView"
runat="server"
AutoGenerateRows="False"
Height="50px"
Width="207px"
DataSourceID="SqlDataSourceDetails"
DataKeyNames="ID"
OnItemCommand="DetailsViewDetails_ItemCommand">
<Fields>
你能告诉我要包括哪些附加属性,这样这样的编码可以“看到”DetailsView 中的字段吗?
Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs)
Select Case e.CommandName
Case "Add"
Case "Edit"
ButtonAddNewAttendance.Enabled = False
Case "Delete"
Case "Update"
ButtonAddNewAttendance.Enabled = True
Case "Insert"
Case "New"
Dim txtBox As TextBox
txtBox = DetailsView.FindControl("TextBoxDateAttendanceTakenInsert")
txtBox.Text = DateTime.Now
Dim drpValue As DropDownList
drpValue = DetailsView.FindControl("DropDownListClassInsert")
drpValue.SelectedValue = 1
End Select
End Sub
目前 FindControl 在 DetailsView 中找不到任何字段并给出 Null 引用错误。
- 更新 *
ItemCommand 不是放置编码的正确位置。
我发现要让它工作,需要添加 OnDataBinding,如下所示,并确保代码隐藏文件中有一个处理程序,如下所示。
InsertItemTemplate 标记:
<InsertItemTemplate>
<asp:DropDownList
ID="DropDownListClassInsert"
Runat="server"
DataSourceID="SqlDataSourceClasses"
DataTextField = "ClassName"
DataValueField="ID"
SelectedValue='<%# Bind("ClassID") %>'
AppendDataBoundItems="True"
ForeColor="Blue"
OnDataBinding="DropDownListClassInsert_DataBinding">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorInsertClass" runat="server" ControlToValidate="DropDownListClassInsert"
ErrorMessage="Please select a Class here." Font-Bold="True" Font-Italic="True" ForeColor="Red"
SetFocusOnError="True" Display="Dynamic">
</asp:RequiredFieldValidator>
</InsertItemTemplate>
代码隐藏文件中的处理程序:
Protected Sub DropDownListClassInsert_DataBinding(sender As Object, e As EventArgs)
Dim drpValue As DropDownList
drpValue = DetailsView.FindControl("DropDownListClassInsert")
drpValue.SelectedValue = intCurrentClassID
End Sub
注意:intCurrentClassID 声明为:
Public Shared intCurrentClassID As Integer = Nothing
后:
Public Class
我希望这可以帮助其他有同样问题的人。