I need an advice how to correct my code. I am using FindControl method to find TextBox inside Repeater. This is my markup:
<asp:Repeater ID="Repeater1">
HERE ARE SOME OTHER DATA
<ItemTemplate>
<asp:FormView ID="FormViewAddComment" runat="server"
DataSourceID="SqlDataSourceInsertComments" DefaultMode="Insert"
OnItemInserted="FormViewAddComment_ItemInserted"
OnItemInserting="FormViewAddComment_ItemInserting">
<InsertItemTemplate>
<asp:TextBox ID="txtAddComment" runat="server" CssClass="textbox"
Text='<%# Bind("CommentText") %>' Width="200px" />
<asp:Button ID="btnAddComment" runat="server" CssClass="button"
Text="Comment" CommandName="Insert" CausesValidation="false"/>
</InsertItemTemplate>
</asp:FormView>
</ItemTemplate>
</asp:Repeater>
And this is my code behind:
Protected Sub FormViewAddComment_ItemInserting(sender As Object, e As FormViewInsertEventArgs)
Dim FormView As FormView = DirectCast(Repeater1.FindControl("FormViewAddComment"), FormView)
Dim Comment As TextBox = DirectCast(FormView.FindControl("txtAddComment"), TextBox)
If Comment.Text = "" Then
Exit Sub
End If
End Sub
The Comment TextBox is not found and the code throws an Object reference error when it tries to access the Text property.
You can find the textbox inside it using ItemDataBound event.
Thanks
You are accessing "txtAddComment" which is there in FormView,then why are you finding FormView in Repeater and then again in textbox in that...you can directly find out it...
Protected Sub FormViewAddComment_ItemInserting(sender As Object, e As FormViewInsertEventArgs)
If (FormView1.CurrentMode == FormViewMode.Insert)
Dim Comment As TextBox = DirectCast(FormViewAddComment.FindControl("txtAddComment"), TextBox)
If Comment.Text = "" Then
Exit Sub
End If
End Sub
EDIT:-
My point is that you are writting the code in ItemInserting Event of FormView,so there you can directly find the FormView.I would suggest to use NamingContainer property in oredr to find the FormView which has trigged the event,by this way you can find the FormView then you can easily find the TextBox in it.
There is example of NamingContainer for Gridview Here
Related
I have a Gridview column called "Path" and when the user clicks on it I want it to pass that value of the "Path" cell to a sub procedure to execute the following code,
process.start(Path)
Currently the table is filled via SQL query and the "Path" is clickable but it wants to take me to URL which won't work for my situation. I also tried the Hyperlink column as well but was having the same problem. Any guidance would be appreciated! Thanks in advance.
You could use a LinkButton instead of a HyperLink.
Set the CommandArgument on the LinkButton, you could use either the GridView.RowCommand event handler or a LinkButton.OnClick event handler to call your sub.
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" OnRowCommand="gridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Path">
<ItemTemplate>
<asp:LinkButton ID="lbPath" runat="server" CommandArgument="<%# Eval("Path")%>" OnClick="lbPath_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in code behind:
Protected Sub lbPath_Click(sender As Object, e As EventArgs)
Dim linkButton As LinkButton = CType(sender, LinkButton)
Process.Start(linkButton.CommandArgument)
End Sub
For reference
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.110).aspx
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.
I believe that you want to use the Fields property instead of FindControl. Once you have the DataControlField, you can cast it to the appropriate control type (i.e. CheckBoxField).
When an ASP.Net DetailsView data is first displayed, can you tell me how to populate the variable shown in this coding?
I already tried this in the code-behind file but was shown an error that:
Object reference not set to an instance of an object.
This is the coding:
Protected Sub DetailsViewDetails_DataBound(sender As Object, e As EventArgs) Handles DetailsViewDetails.DataBound
Dim txtOriginalRegistrationFee As TextBox
If DetailsViewDetails.CurrentMode = DetailsViewMode.Edit Then
txtOriginalRegistrationFee = FindControl("TextBoxRegistrationFee")
If String.IsNullOrEmpty(txtOriginalRegistrationFee.Text) = False Then
MsgBox(txtOriginalRegistrationFee)
End If
End If
End Sub
This is from the aspx file:
<asp:TemplateField HeaderText="RegistrationFee" SortExpression="RegistrationFee">
<EditItemTemplate>
<asp:TextBox ID="TextBoxRegistrationFee" runat="server" Text='<%# Eval("RegistrationFee") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBoxRegistrationFee" runat="server" Text='<%# Bind("RegistrationFee") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelRegistrationFee" runat="server" Text='<%# Bind("RegistrationFee", "{0:c}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle ForeColor="Blue" />
</asp:TemplateField>
* Update *
I tried using this coding updated based on your help but still get the "Object reference not set to an instance of an object." error when clicking the edit button of the DetailsView.
The FindControl function needs a control to search otherwise it will be searching the page (or content) level controls.
Try
txtOriginalRegistrationFee = DetailsViewDetails.FindControl("TextBoxRegistrationFee")
By the way your line with the MsgBox function will not work either. MsgBox is for windows forms and will not work on the web. You must use javascript for that type of functionality. Plus, that function takes a string, not a control.
I don't work in VB so bear with me.... The template is only rendered if your details view is in insert mode.
Dim txtOriginalRegistrationFee As TextBox
If DetailsViewDetails.CurrentMode = DetailsViewMode.Insert Then
txtOriginalRegistrationFee = FindControl("TextBoxRegistrationFee")
If String.IsNullOrEmpty(txtOriginalRegistrationFee.Text) = False Then
MsgBox(txtOriginalRegistrationFee)
End If
End If
Here is the setup:
I programmatically populate my gridview using LINQ to SQL query. Then I enter the edit mode and want to replace some standard TextBox controls with DropDownLists like this:
'excerpt from GridView1_RowEditing
Dim ddlist1 As New DropDownList
Dim res1 = From items1 In mydb.Items
Select items1.Col10
ddlist1.DataSource = res1
ddlist1.DataBind()
GridView1.Rows.Item(0).Cells(1).Controls.Add(ddlist1)
At this moment I have my gridview showing standard textbox control and new DDList control (in the Column 1).
The problem is -- I cant read the value from DDList in the RowUpdating method. It seems like DDList control is not in the GridView1.Rows.Item(0).Cells(1).Controls collection.
RowUpdating method sees only standard TextBox control and can read it's value.
Any suggestions are welcome. I just don't understand something here :(
Use TemplateField, and then you can locate your dropdown using FindControl
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
...
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
Dim ddl = CType(GridView1.Rows(e.RowIndex).Cells(1).FindControl("DropDownList1"), DropDownList)
End Sub
Okay, so I'm having issues getting the value of a DropDownList that's inside of a TemplateField when updating my GridView. Originally I was using the RowCommand event to check the command name and then performing the appropriate task (update/delete), but I had problems with the event firing twice, so I switched it out for separate events (RowUpdating, RowDeleting). After doing this, FindControl is returning null every time. Just FYI, the gridview is inside of an UpdatePanel that has an AsyncPostBackTriggers for RowEditing, RowUpdating and RowDeleting events.
Here's my TemplateField inside of the GridView:
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:Label
ID="lblMedTypeEdit"
Text='<%# Bind("medDesc") %>'
runat="server">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlMedTypeEdit"
DataSourceID="srcMedTypes"
SelectedValue='<%# Bind("medtype") %>'
runat="server"
DataTextField="medDesc"
DataValueField="medCode">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
Here is the code I'm using inside of
Protected Sub gvCurrentMeds_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvCurrentMeds.RowUpdating
Dim intRowIndex As Integer = e.RowIndex
Dim ddlMedType As DropDownList = CType(Me.gvCurrentMeds.Rows(intRowIndex).Cells(1).FindControl("ddlMedTypeEdit"),DropDownList)
End Sub
I also tried using a recursive function to find the control (below), but it is still returning back null.
Public Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ID = id Then
Return root
End If
For Each c As Control In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next
Return Nothing
End Function
If you just want to know what the new value of the dropdown is, this is already provided for you in the NewValues property of the GridViewUpdateEventArgs object passed to the event handler.
In your example, e.NewValues["medtype"] should be the updated value.
You've already specified <%# Bind(...) %> on the dropdown, so ASP.NET will do the work of finding the controls and getting the new values for you - you don't have to plumb the control hierarchy yourself.