I'm looking to get FindControl to "see" controls in an ASP.Net DetailsView from a VB.Net code-behind file. It doesn't find any of them.
The markup for the page is using a 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">
Currently the attributes of a our DetailsView looks like this:
<asp:DetailsView
ID="DetailsView"
runat="server"
AutoGenerateRows="False"
Height="50px"
Width="207px"
DataSourceID="SqlDataSourceDetails"
DataKeyNames="ID"
OnItemCommand="DetailsViewDetails_ItemCommand">
<Fields>
Can you tell me what additional attributes to include so coding like this can "see" the fields in the 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
Currently FindControl can't find any of the fields in the DetailsView and gives a Null reference error.
- UPDATE *
ItemCommand is not the correct place to put the coding.
I found out that to get this to work, OnDataBinding needs to be added as shown here plus making sure there is a handler in the code-behind file as shown below.
InsertItemTemplate markup:
<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>
Handler in the code-behind file:
Protected Sub DropDownListClassInsert_DataBinding(sender As Object, e As EventArgs)
Dim drpValue As DropDownList
drpValue = DetailsView.FindControl("DropDownListClassInsert")
drpValue.SelectedValue = intCurrentClassID
End Sub
Note: intCurrentClassID is declared as:
Public Shared intCurrentClassID As Integer = Nothing
after:
Public Class
I hope this helps others who had the same issues.