asp.net textbox array with events - asp.net

I have the following code in the page source:
<asp:Button ID="Button1" runat="server" Text="Button" />
And in code behind page:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 9
Dim box As New TextBox()
box.ID = "textBox" + CStr(i)
box.Width = 20
box.Text = CStr(i)
box.TabIndex = CShort(i + 1)
AddHandler box.TextChanged, AddressOf ClickBox
panel1.Controls.Add(box)
Next
End Sub
Private Sub ClickBox(sender As Object, e As EventArgs)
Dim boxUsed = DirectCast(sender, TextBox)
boxUsed.BackColor = Drawing.Color.Crimson
End Sub
The problem is TextChange event for texboxes doesn't fire.

Two things. First:
box.AutoPostBack = True
Second:
Since you're creating textboxes dynamically, they will be gone between every postback, unless you re-create them in the Page_Load event.

Related

how to find the button id inside the Gridview which is in update panel?

i am not able to find the id of the update button is thee any way to
find the update button id which is inside the gridview and the grid is
inside the update panel.
Script register is written is page load. i am writing this so as
currently update button is firing on second click
ASPX code
<asp:UpdatePanel ID="UpdatePanelSubMeter" runat="server">
<ContentTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />
</EditItemTemplate>
</asp:UpdatePanel>
vb.net code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.ErrorLabel.Text = String.Empty
Me.ErrorLabel.Visible = False
Dim pageName = HttpContext.Current.Request.Url.AbsoluteUri
If (Not Page.IsPostBack) Then
tblNAbers.Visible = True
BindBLDGDropDown("adonepudi")
End If
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
end sub
Protected Sub ddlBldgId_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBldgId.SelectedIndexChanged
If ddlBldgId.SelectedItem.Value != -1 Then
BindGridSubMeter()
end sub
Protected Sub BindGridSubMeter()
Dim conMRI As New ConnectionMRI()
Dim ds As DataSet = conMRI.NabersSubMetergetData(ddlBldgId.SelectedItem.Value, ddlRating.SelectedItem.Value)
TextExclusions.Text = ds.Tables(1).Rows(0).Item(0).ToString()
UpdatePanelExclusions.update()
With GridSubMeter
.DataSource = ds.Tables(0)
.DataBind()
End With
End Sub
Protected Sub GridSubMeter_RowEditing(sender As Object, e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridSubMeter.RowEditing
GridSubMeter.EditIndex = e.NewEditIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubmeter_PageIndexChanging(sender As Object, e4 As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridSubMeter.PageIndexChanging
GridSubMeter.PageIndex = e4.NewPageIndex
Me.BindGridSubMeter()
End Sub
Protected Sub GridSubMeter_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridSubMeter.RowUpdating
Dim txtMeterIdn As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txtMeterIdn"), TextBox)
Dim txCTFact As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txCTFact"), TextBox)
Dim txReadStartDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadStartDate"), TextBox)
Dim txReadEndDate As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txReadEndDate"), TextBox)
Dim txStartKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txStartKwh"), TextBox)
Dim txEndKwh As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txEndKwh"), TextBox)
Dim txBillPer As TextBox = CType(GridSubMeter.Rows(e.RowIndex).FindControl("txBillPer"), TextBox)
Dim MeterIdn As String = txtMeterIdn.Text.Trim.ToString()
Dim CTFact As Decimal = Convert.ToDecimal(txCTFact.Text)
Dim ReadStartDate As Date = Date.Parse(txReadStartDate.Text)
Dim ReadEndDate As Date = Date.Parse(txReadEndDate.Text)
Dim StartKwh As Decimal = Convert.ToDecimal(txStartKwh.Text)
Dim EndKwh As Decimal = Convert.ToDecimal(txEndKwh.Text)
Dim billper As Decimal = Convert.ToDecimal(txBillPer.Text)
Dim leasid As String = GridSubMeter.Rows(e.RowIndex).Cells(0).Text.Trim.ToString()
Dim suitid As String = GridSubMeter.Rows(e.RowIndex).Cells(1).Text.Trim.ToString()
Dim occupant As String = GridSubMeter.Rows(e.RowIndex).Cells(2).Text.Trim.ToString()
GridSubMeter.EditIndex = -1
Dim conMRI As New ConnectionMRI()
conMRI.NaberSubmeter(ddlBldgId.SelectedItem.Value, leasid, suitid, occupant, MeterIdn, CTFact, ReadStartDate, ReadEndDate, StartKwh, EndKwh, billper)
Me.BindGridSubMeter()
End Sub
Try removing
For Each gvr As GridViewRow In GridSubMeter.Rows
If gvr.RowType = DataControlRowType.DataRow Then
Dim button As Button = CType(gvr.FindControl("btn_Update"), Button)
If Not (button Is Nothing) Then
ScriptManager.GetCurrent(Me).RegisterPostBackControl(button)
from page load and paste it in BindGridSubMeter at the end.
Try this
For Each gr As GridViewRow In Grid_Records.Rows
Dim bt As Button = DirectCast(gr.Cells(0).FindControl("btn_Update"), Button)
Dim here As bt.properties
Next

Writing a passed Array via session into Label isn't working

I am trying to take an array of string (Filled from a listbox on a previous page and passed via Session) and display it in a label,this is how i got the array:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim x = ListBox1.GetSelectedIndices.Count
Dim ListPNames(x) As String
Dim i As Integer
i = 0
For Each item As String In ListBox1.GetSelectedIndices
ListPNames(i) = (ListBox1.SelectedItem).ToString
i = i + 1
Next
Session("SlctdPhones") = ListPNames(x)
Response.Redirect("CheckOut.aspx")
End Sub
And this is how i am trying to display it :
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim i As Integer
Label3.Text = ""
For i = 0 To SlctdPhones.Length - 1
Label3.Text += SlctdPhones(i).ToString() + Environment.NewLine
Next
End Sub
It is giving me an error :Object reference not set to an instance of an object. when it reaches the SlctdPhones.Length - 1 Line!!
i don't know how i can fix it ,also is my array code correct(Is everything being stored correctly in it?)
You declare the For loop like this:
For Each item In ...
But then never use the item variable in the body of the loop. Instead, you keep using the same SelectedItem property. You want to change that whole method to look like this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim PNames As New List(Of String)()
For Each index As Integer In ListBox1.GetSelectedIndices
PNames.Add(ListBox1.Items(index).Value)
Next
Session("SlctdPhones") = PNames
Response.Redirect("CheckOut.aspx")
End Sub
With that fixed, the Page_Load can do this:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones As List(Of String) = TryCast(Session.Item("SlctdPhones"), List(Of String))
If SlctdPhones Is Nothing OrElse SlctdPhones.Length = 0 Then
'Something went wrong here!
Return
End If
Label3.Text = String.Join("<br/>", SlctdPhones.ToArray())
End Sub
But I'd really love to see you use a data control rather than stuffing <br/>s into a label. Here's markup for a ListView:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><%# Container.DataItem.ToString() %></li>
</ItemTemplate>
<EmptyDataTemplate>
<p>Nothing here.</p>
</EmptyDataTemplate>
</asp:ListView>
And then Page_Load is even simpler:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.DataSource = Session.Item("SlctdPhones")
ListView1.DataBind()
End Sub
On display page, use Literal instead of Label
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim result as String = string.Join("<br>", SlctdPhones) 'Instead of <br> try Environment.NewLine as well
YourLitetal = result
Hope this helps!

How do i give a value a TextBox create dynamically when i click and doubleClick? vb.net

I have text box create like that:
Dim Result1 As New TextBox
Result1.ID = "BOX_Result" & a & "_" & i
I want when i click on that textbox to write "OK" and when i double click in cell to put NOT/OK
Important! The TextBox is created Dynamically if i try Result.Click doesn't work, get ne that error: "Result1.Click display error: "Click is not an event of 'System.Web.UI.WebControls.TextBox' "
I try like that but doesn't work:
AddHandler Result1.Click, AddressOf Me.Result1_Click
Private Sub Result1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Result1.Text = "OK"
End Sub
I want when a person click on that textbox created dynamically but doesn't work click. Thanks for help
You can add these lines to your TextBox definition:
Result1.Attributes.Add("onclick", "this.value = 'OK';")
Result1.Attributes.Add("ondblclick", "this.value = 'NOT/OK';")
In this code, the text "NOT/OK" is displayed when the user double-clicks in the TextBox. In your question, you talk about a double-click "in cell". If that "cell" is not the TextBox, please give some indication of what kind of control it is.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim tb As New TextBox 'Create the new TextBox
AddHandler tb.DoubleClick, AddressOf TB_DoubleClick 'Add a handler to the textbox`s DoubleClick event
AddHandler tb.Click, AddressOf TB_Click
'Set any other properties of textbox you want here....
Me.Controls.Add(tb) 'Add the textbox to the forms controls
End Sub
'This is the textbox Click event handler sub
Private Sub TB_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim tb As TextBox = DirectCast(sender, TextBox) 'Cast the (sender) into a textbox to get access to the textbox`s properties
Result1.Text = "OK"
End Sub
'This is the textbox DoubleClick event handler sub
Private Sub TB_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim tb As TextBox = DirectCast(sender, TextBox) 'Cast the (sender) into a textbox to get access to the textbox`s properties
Result1.Text = "NOT OK"
End Sub
I have create a simple exemple for you :
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Result1 As New TextBox
Result1.Text = "BOX_Result"
Dim loc As New Point With {.Y = 117, .X = 111}
Result1.Location = loc
Me.Controls.Add(Result1)
AddHandler Result1.Click, AddressOf Me.Result1_Click
End Sub
Private Sub Result1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txt As TextBox = sender
sender.Text = "OK"
End Sub
End Class
Hope that you want

Gridview rowcommand event not firing in dynamically added usercontrol

I have a usercontrol with gridview and rowcommand event.
This usercontrol is added dynamically using LoadControl on a button click of a page. The gridview's rowcommand doesn't fire.
Here is the code that loads the usercontrol on button click:
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
'<ucTitle:SearchList ID="ucSearchList" runat="server" Visible="false" />
Dim ucSearchList As TitleSearchList = LoadControl("~/Controls/TitleSearchList.ascx")
ucSearchList.ISBN = txtSearchISBN.Text
ucSearchList.LoadTitleSearchList()
pnlSearchResults.Controls.Add(ucSearchList)
End Sub
And here is the code in usercontrol
Public Class TitleSearchList
Inherits System.Web.UI.UserControl
Public Property ISBN As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadTitleSearchList()
End If
End Sub
Public Sub LoadTitleSearchList()
Dim _isbn As String = ISBN
Dim titles As New List(Of Title)
titles = New List(Of Title) From {
New Title With {.ISBN = _isbn, .TitleName = "Title check"},
New Title With {.ISBN = _isbn, .TitleName = "Title check"},
New Title With {.ISBN = _isbn, .TitleName = "Title check"},
New Title With {.ISBN = _isbn, .TitleName = "Title check"}
}
gvTitle.DataSource = titles
gvTitle.DataBind()
End Sub
Public Sub gvTitle_Rowcommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles gvTitle.RowCommand
If e.CommandName = "TitleDetail" Then
Response.Redirect("TitleSearch.aspx?isbn=" & e.CommandArgument().ToString())
End If
End Sub
End Class
Events in GridViews that are added dynamically in a UserControl get a little ugly. Since UserControls that are added dynamically have to be re-added on the post-back, you have to rebind the GridView DataSource, which makes you lose out on automatically getting those Events fired for you. That being said, you can still pull it off with some parsing of the __EVENTTARGET of the Form.
Add a HiddenField that tells you whether or not you need to re-add the UserControl. Add this in your Page_Load Event Handler:
If CBool(hdnTitleSearchActive.Value) = True Then
AddSearchListToPanel()
End If
Call AddSearchListToPanel() in your btnSearch_Click Event Handler.
Now this implementation of AddSearchListToPanel can be cleaned up some, but this should be good enough to get you going. Note that the Button triggering the GridView Command in my example has the ID of lbtTest. You will have to adjust based on the ID that you are using.
Private Sub AddSearchListToPanel()
Dim ucSearchList As TitleSearchList = LoadControl("~/Controls/TitleSearchList.ascx")
ucSearchList.ISBN = txtSearchISBN.Text
ucSearchList.LoadTitleSearchList()
pnlSearchResults.Controls.Add(ucSearchList)
hdnTitleSearchActive.Value = True
Dim strEventTarget As String = HttpContext.Current.Request.Form("__EVENTTARGET")
If Not strEventTarget Is Nothing AndAlso strEventTarget.Contains("gvTitle$") AndAlso _
strEventTarget.Contains("$lbtTest") Then
'Value example = gvTitle$ctl02$lbtTest
Dim intRowNumber As Integer = (CInt(strEventTarget.Substring(11, 2)) - 1)
Dim lbtCommandSource As LinkButton = CType(CType(ucSearchList.FindControl("gvTitle"), GridView).Rows(intRowNumber).FindControl("lbtTest"), LinkButton)
Dim objCommandEventArguments As New CommandEventArgs(lbtCommandSource.CommandName, lbtCommandSource.CommandArgument)
Dim objGridViewCommandEventArgs As New GridViewCommandEventArgs(lbtCommandSource, objCommandEventArguments)
ucSearchList.gvTitle_Rowcommand(lbtCommandSource, objGridViewCommandEventArgs)
End If
End Sub

How to reference a DropDownList inside a DetailsView?

I have a DetailsView which contains several text boxes and also a DropDownList.
Now, what I want to do is to write an SelectedIndexChanged event for that DropDownList, but my problem is that I cannot reach it anymore/reference it.
If I just put a DropDownList right on the form it´s no problem but now winds it is inside the DetailsView it seems impossible to reach it.
Any suggestions?
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging1(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I know this is not right, but its as far as I get. I would want to just Write the code within the following sub but it just will not work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListContractType.SelectedIndexChanged
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
You did not post the markup for the dropdownlist, it should be like below (Attached the method to the event):
<asp:DropDownList ID="DropDownListContractType" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownListContractType_SelectedIndexChanged">
<asp:ListItem Text="Kjøp" Value="2"></asp:ListItem>
<asp:ListItem Text="Leasing" Value="1"></asp:ListItem>
</asp:DropDownList>
Your code also have some issues:
Should be DropDownList.SelectedItem.Text instead of
DropDownList.Text.
You have to cast the sender to DropDownList in DropDownListContractType_SelectedIndexChanged method.
You have to find the NamingContainer of DropDownList in DropDownListContractType_SelectedIndexChanged method
If you have the following code, it should work:
Protected Sub DropDownListContractType_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim DropDownListContractType As DropDownList = DirectCast(sender, DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(DropDownListContractType.NamingContainer.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Leasing" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
Protected Sub DetailsViewAvtaleInfo_PageIndexChanging(sender As Object, e As DetailsViewPageEventArgs) Handles DetailsViewAvtaleInfo.PageIndexChanging
Dim DropDownListContractType As DropDownList = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("DropDownListContractType"), DropDownList)
Dim TextBoxLeasingPriceMonth As TextBox = DirectCast(Me.DetailsViewAvtaleInfo.FindControl("TextBoxLeasingPriceMonth"), TextBox)
If DropDownListContractType.SelectedItem.Text = "Kjøp" Then
TextBoxLeasingPriceMonth.Visible = False
End If
End Sub
I have tested the code above. If you have any issue, try to copy/paste the markup and code.
You can download my test project to compare with yours here.

Resources