Reference specific asp.net control using vb.net code bhind variable - asp.net

I have read through many different solutions both here on SO and other sites but this keeps eluding me.
I am trying to reference an asp.net textbox and image button from code behind vb.net.
I have tried this code but the variable tBox says it equal is nothing.
Dim callBtn As ImageButton = CType(sender, ImageButton)
Dim tBox As TextBox
Dim iButton As ImageButton
Dim cNumber As Integer = Convert.ToInt32(callBtn.ID.Substring(11))
tBox = CType(Page.FindControl("TextBox" & cNumber), TextBox)
'The line below is commented out because it did not work either but
was the first one I tried
'tBox = DirectCast(Page.FindControl("TextBox" & cNumber), TextBox)
tBox.Text = "" <--- On this line tBox is nothing
tBox.Visible = False
I have placed a break point on the tBox.Text line and tBox equals nothing.
How can I reference the text box from a variable? I also need to reference and image button as well but need to get this one to work first.
If there is a question on here that exactly answers this please point me to it as I could not find one.
Edit: Update
Here is the code that creates a textbox and image button.
<asp:ImageButton ID="ImageButton1" runat="server" Visible="false" OnClick="removeFile" ImageUrl="~/Images/red-x-md20x20.png" ImageAlign="Top" ToolTip="Click To Remove File" /> 
<asp:TextBox ID="TextBox1" runat="server" Visible="false" Width="300px" />

It turns out that I was not looking for the right Name. Being on a content page I had to reference the master page first.
I used the following:
Dim ctrlNameT As String = "ctl00$ContentPlaceHolderRight$TextBox" & cNumber
This did the trick!

Related

How to get a RadAutoCompleteBox in a RadGrid to display bound value in Edit mode?

I expect that I'm just doing something just a smidge wrong (newly moved to web-dev from winforms, and new to Telerik). I'm updating an app that primarily has a RadGrid displaying GridBoundColumns that display text normally and turn to textboxes when the row is being edited. I'm converting one of these columns to a GridTemplateColumn that uses a RadAutoCompleteBox in the EditItemTemplate. In normal (display?) mode, the text bound to the item displays correctly, but when the row enters edit mode, the AutoCompleteBox is properly bound to its own data source, but doesn't display the grid-row's value for that column. How do I do that?
I have:
<telerik:GridTemplateColumn UniqueName="PartNumber" HeaderText="Part Number" ItemStyle-CssClass="editWidth"
FilterControlAltText="Filter PartNumber column" FilterControlWidth="85%">
<ItemTemplate><%#DataBinder.Eval(Container.DataItem, "PartNumber")%></ItemTemplate>
<EditItemTemplate>
<%#DataBinder.Eval(Container.DataItem, "PartNumber")%>
<telerik:RadAutoCompleteBox runat="server" ID="racbPN" DataSourceID="ItemIdSource" DataTextField="IMA_ItemID"
HighlightFirstMatch="true" InputType="Text" TextSettings-SelectionMode="Single" MaxResultCount="200" MinFilterLength="4"
Delimiter="" DropDownHeight="300px" DropDownWidth="200px">
</telerik:RadAutoCompleteBox>
</EditItemTemplate>
<HeaderStyle Width="190px"></HeaderStyle>
</telerik:GridTemplateColumn>
Scouring the Telerik forums, I've seen some references to putting code in the ItemDataBound event. That code is typically in C# and my converted-to-VB implementations never work. I don't know if I'm mistranslating or they're not really the answer for my situation, but here's an example of something I've tried in the code-behind:
If e.Item.IsInEditMode Then
Dim item As GridEditableItem = e.Item
If Not e.Item Is GetType(IGridInsertItem) Then
Dim auto As RadAutoCompleteBox = CType(item.FindControl("racbPN"), RadAutoCompleteBox)
auto.Entries.Add(New AutoCompleteBoxEntry(item("PartNumber").Text, item("GSIS_AMRKey").Text))
End If
End If
Thanks for taking a look and please let me know what other info I need to provide if I've left something important out.
(Should radautocompletebox be a valid tag?)
Telerik tech support got back to me with an answer. The code I listed above in the OnItemDataBound event was almost right. This works:
If e.Item.IsInEditMode Then
If Not e.Item Is GetType(IGridInsertItem) Then
Dim partNumber As String = DirectCast(e.Item.DataItem, DataRowView)("PartNumber").ToString
Dim auto As RadAutoCompleteBox = DirectCast(e.Item.FindControl("racbPN"), RadAutoCompleteBox)
auto.Entries.Add(New AutoCompleteBoxEntry(partNumber))
End If
End If

Using gridview in an updatepanel and want the link column to fetch correct data

I have created my own Application that displays a gridview with several lines. The first column in the grid is a link button. My problem is with the use of the updatepanel functioanlity, since the gridview if not in the update panel works ok, and i can click the link for a line and that line's coulmns are being placed in textboxes below outside the gridview. This is done with a selectedindexchange function.
However when adding:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<asp:UpdatePanel runat="server" ID="updatePanel1" UpdateMode="always" >
<ContentTemplate>
--gridview code--
</ContentTemplate>
</asp:UpdatePanel>
it wont do any action as before. I have no idea why. My code that is run basically for the post to the text boxes are like this:
Protected Sub allCases_OnSelectedIndexChanged(sender As Object, e As EventArgs)
Dim row As GridViewRow = allCases.SelectedRow
txtcase.Text = row.Cells(1).Text()
txtsub.Text = TryCast(row.FindControl("lblsubName"), Label).Text
txtuser.Text = TryCast(row.FindControl("lbluserName"), Label).Text
oDato.Text = row.Cells(9).Text
lDato.Text = "Case closed!"
txttype.Text = TryCast(row.FindControl("lblcaseType"), Label).Text
txtregBy.Text = TryCast(row.FindControl("lblcaseRegby"), Label).Text
txttopic.Text = TryCast(row.FindControl("lblcaseTopic"), Label).Text
txtDesc.Text = TryCast(row.FindControl("lblcaseDesc"), Label).Text
txtSolu.Text = TryCast(row.FindControl("lblcaseSolu"), Label).Text
'lblinfo.Text = row.Cells(6).Text
End Sub
I suspect it to be becasue of some reload of the page or something like that, but have really no idea. Any help here would be very appreciated.
If you need to see more of the code, let me know.
Thank you for pointing me to the right place Mason! It helped putting everything in the update panel including the textboxes. Now it Works.

Create labels dynamicly on ASP.NET (VB)

I want to create labels in my page dynamicly, for example the user will choose in a textbox the number of labels, and I will display the number of this label with .text = "XYZ".
Thanks.
The quick and dirty method (this example adds 10 labels and literals to a PlaceHolder on an ASP.NET page:
Dim c As Integer = 0
While c < 10
Dim lab As New Label()
Dim ltr As New Literal()
lab.Text = c.ToString()
ltr.Text = "<br/>"
PlaceHolder1.Controls.Add(lab)
PlaceHolder1.Controls.Add(ltr)
C+=1
End While
Look at using a Repeater control:
Using the ASP.NET Repeater Control
Data Repeater Controls in ASP.NET
There's a number of things that will need to be done to make this work, but to simply dynamically create controls and add them to the page, you will need a Placeholder on your ASPX page:
<asp:TextBox ID="txtLabelCount" runat="server" />
<asp:Button ID="btnCreate" runat="server" Text="Create" /><br />
<asp:Placeholder ID="PlaceHolder1" runat="server" />
Then, in btnCreate's click event handler:
' Number of labels to create. txtLabelCount should be validated to ensure only integers are passed into it
Dim labelCount As Integer = txtLabelCount.Text
For i As Integer = 0 To labelCount - 1
' Create the label control and set its text attribute
Dim Label1 As New Label
Label1.Text = "XYZ"
Dim Literal1 As New Literal
Literal1.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label1)
PlaceHolder1.Controls.Add(Literal1)
Next

ASP.Net CustomValidator in GridView is not fired

I got a Gridview in an UpdatePanel with this EditTemplate:
<edititemtemplate>
<asp:textbox id="txtDistFrom" runat="server" text='<%# Bind("distFrom") %>' width="30" />
<asp:CustomValidator ID="valDistFrom" ValidateEmptyText="True" OnServerValidate="valDistFromTo_ServerValidate" ControlToValidate="txtDistFrom" Text="Missing" ToolTip="Invalid" Display="Dynamic" runat="server" />
</edititemtemplate>
And a simple Server-side function:
Protected Sub valDistFromTo_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim cv As CustomValidator = CType(source, CustomValidator)
Dim gvr As GridViewRow = cv.NamingContainer
Dim tbV As UI.WebControls.TextBox = gvr.FindControl("txtDistFrom")
If tbV.Text <> "" Then
args.IsValid = False
cv.ErrorMessage = "inhalt ist " & tbV.Text
End If
End Sub
But when debugging this code the server-side function is not fired, whatever it does. It seems it has to do with the gridview, so I cannot access the control directly by its id. Any suggestions?
If you modify your VB to:
Protected Sub valDistFromTo_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
Dim cv As CustomValidator = CType(source, CustomValidator)
If args.Value <> "" Then
args.IsValid = False
cv.ErrorMessage = "inhalt ist " & args.Value
End If
End Sub
It should work. Note that I'm using args.Value. I use CustomValidators and TextBox within EditTemplates with ControlToValidate set to the TextBox ID all the time and it works, you just can't get the TextBox object the way you're trying it. I think this is far less of a pain and much cleaner than messing around with RowUpdating Event as suggested in TGnat's answer.
In this case you can use a required field validator. Which should work just fine in a grid.
For server side validation I would move the custom validator outside the grid entirely and leave the ControlToValidate property blank. You can move your validation to the RowUpdating event of the grid and set any error messages on the custom validator. Rmember to set the validators IsValid property appropriately.
The problem is related to the ControlToValidate property, because the ID of your text box is not used in repeating elements like GridView, ListView and Repeater. In other words: You have stumbled upon a limitation in ASP.NET's engine.
I am not sure how to solve this problem, though. You might be able do it, by adding the CustomValidator programmatically by attaching a method to the GridView's OnRowBound method.
This article might provide an answer This article might provide an answer: Integrating Asp.Net Validation Controls with GridView at run-time.
I also tend to think that ControlToValidate is the problem. .NET changes the ID of that control at runtime and the custom validator probably isn't picking it up.
I would try adding the customvalidator on RowCreated or RowDatabound using the FindControl()
I had the same problem. When I explicitly set this property in my customvalidator, the server side code fired:
EnableClientScript="false"

Setting LinkButton Title in ASP.Net Wizard Sidebar Template

Playing around with customizing the appearance of the Wizard control in ASP.Net, and I've found out how to disable the sidebar buttons using the SideBarTemplate and catching the OnItemDataBound event. All pretty easy. What I want to do now is to modify the text of the rendered LinkButton to prefix the step name with something like ">>" for the current step.
So, in my ItemDataBound event handler for the SideBarList, I have the following code:
Dim stepCurrent As WizardStep = e.Item.DataItem
Dim linkCurrent As LinkButton = e.Item.FindControl("SideBarButton")
If Not stepCurrent Is Nothing Then
Trace.Write("SideBar", "Current Step = " & stepCurrent.Wizard.ActiveStep.Name)
Trace.Write("Sidebar", "Link Button = " & linkCurrent.Text)
linkCurrent.Enabled = False
If stepCurrent.Wizard.ActiveStepIndex = e.Item.ItemIndex Then
linkCurrent.Style.Add(HtmlTextWriterStyle.Color, "#000000")
linkCurrent.Style.Add(HtmlTextWriterStyle.FontWeight, "bold")
linkCurrent.Text.Insert(0, ">> ")
End If
End If
However, what I find is the trace output is showing an empty string for the lunkbutton text, but the style changes work.
Am I trying to set the text in the wrong place?
Thanks
I did not find any way to change "SideBarButton" text property that is why I added
another link button control in SelectedItemTemplate to DataList and set visible="fasle" in SideBarButton. SelectedItemTemplate will be used to render item in sidebar for current wizard step.
<ItemTemplate>
<asp:LinkButton ID="SideBarButton" runat="server"/>
</ItemTemplate>
<SelectedItemTemplate>
<asp:LinkButton ID="ActiveSideBarButton" runat="server">
<asp:LinkButton Visible="false" ID="SideBarButton"unat="server"/>
</SelectedItemTemplate>
In OnItemDataBound event do something like
Dim stepCurrent As WizardStep = e.Item.DataItem
If stepCurrent.Wizard.ActiveStepIndex = e.Item.ItemIndex Then
Dim linkCurrent As LinkButton = e.Item.FindControl("ActiveSideBarButton")
linkCurrent.Style.Add(HtmlTextWriterStyle.Color, "#000000")
linkCurrent.Style.Add(HtmlTextWriterStyle.FontWeight, "bold")
LinkCurrent.Text = stepCurrent.Title;
linkCurrent.Text.Insert(0, ">> ")
End If
SideBarButton will not be rendered because of visible="false" and only ActiveSideBarButton for current step will be rendered with parameters you need.

Resources