ASP.Net add item to listbox without posting - asp.net

I am trying to add items to a listbox. I have a textbox and a button and when the user enters something into the textbox and hits add, I want to insert a new item the listbox without the page refreshing.
Here is what I have so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="col-xs-6 text-center">
<asp:Label ID="empid" runat="server" Text="Employee ID" CssClass="label-default label "></asp:Label>
<asp:TextBox ID="txtEmployeeID" runat="server" CssClass="form-control"></asp:TextBox>
<div class="col-xs-6">
<asp:Button ID="btnAddEmp" runat="server" Text="Add Emp" CssClass="btn btn-primary top-buffer" Width="100%" />
</div>
<div class="col-xs-6">
<asp:Button ID="btnRemoveEmp" runat="server" Text="Remove Emp" CssClass="btn btn-danger top-buffer" Width="100%" />
</div>
<asp:ListBox ID="listEmps" runat="server"
CssClass="top-buffer add-height"
Width="100%"
ValidationGroup="req"></asp:ListBox>
</div>
</ContentTemplate>
</asp:UpdatePanel>
and here is my button click event
Protected Sub btnAddEmp_Click(sender As Object, e As EventArgs) Handles btnAddEmp.Click
If Not IsPostBack() Then
If listEmps.Items.Count = 0 Then
listEmps.Items.Add(txtEmployeeID.Text)
Else
'check list to see if employee already exists
For i = listEmps.Items.Count - 1 To 0 Step -1
If RTrim(txtEmployeeID.Text) = RTrim(listEmps.Items(i).ToString) Then
'employee already exists within list
Response.Write("<script>alert('Employee ID " & txtEmployeeID.Text.Trim & " has already been added. ')</script>")
txtEmployeeID.Text = ""
Exit Sub
End If
Next
'add to list
listEmps.Items.Add(txtEmployeeID.Text)
End If
End If
End Sub
How can I properly add items to a listbox without refreshing the page?

Remove your If Not IsPostBack() Then check in your button click event. The IsPostBack() is typically only used for the Page_Load event. Since your button is contained in an UpdatePanel the click event should be asynchronous and won't cause a postback.

Related

How to Update Specific update panel and prevent other to be refreshed?

i am trying to add time attendance at dashboard but i have other
update panels with filter tools such as month and year when tick event
of the timer occured the dropdown options collapsed and i can't choose
one of them. i need to update only TimerUpdatePanel not other update
panels the code :
<asp:UpdatePanel ID="TimerUpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<div class="row">
<div class="offset-2 col-md-4">
<div id="timer" class="bg-primary timer-div">
<div>
<h2 id="Timer_Time" runat="server">00:00:00</h2>
<h2 id="Timer_Day" runat="server">-------</h2>
<h2 id="Timer_Date" runat="server">00-00-0000</h2>
</div>
</div>
</div>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" />
</div>
<div class="hr-line-dashed"></div>
<div class="row">
<div class="col-md-4 offset-5" style="padding-top: 12px; letter-spacing: 2px;">
<span id="PunchMsg" runat="server"></span>
<br />
<span id="TimerOption" runat="server"></span>
</div>
<div class="col-md-3">
<h2 id="stopWatch" runat="server"><span></span><span id="Hours"
runat="server">00:00:00
<asp:Button ID="PunchIN" Text="Punch In" runat="server" Visible="true" CssClass="btn btn-primary"
OnClick="PunchIN_Click"></asp:Button>
<asp:Button ID="PunchOut" Text="Punch Out" runat="server" Visible="false" CssClass="btn btn-warning"
OnClick="PunchOut_Click"></asp:Button>
</asp:UpdatePanel>
Protected Sub Timer1_Tick(sender As Object, e As EventArgs)
Dim CurrentDay = DateTime.Now.ToString("dddd")
Dim CurrentDate = DateTime.Now.ToString("dd-MM-yyyy")
Dim CurrentTime = DateTime.Now.ToString("H:mm tt")
Timer_Day.InnerText = CurrentDay
Timer_Date.InnerText = CurrentDate
Timer_Time.InnerText = CurrentTime
If PunchIN.Visible = False AndAlso PunchOut.Visible = True Then
If Session("TimerStatement") <> "" Then
Dim h = Val(Hours.InnerText)
Dim m = Val(Minutes.InnerText)
Dim s = Val(Seconds.InnerText)
s += 1
If s = 60 Then
s = 0
m = m + 1
End If
If m = 60 Then
m = 0
h = h + 1
End If
Hours.InnerText = h.ToString("00")
Minutes.InnerText = m.ToString("00")
Seconds.InnerText = s.ToString("00")
Else
TimerOption.InnerText = "Please select one of the below options first"
End If
End If
TimerUpdatePanel.Update()
End Sub
[this image show filter tools that be collpsed every 1 second][1]
[1]: https://i.stack.imgur.com/QYBCW.jpg
Well, some panel that updates with a timer? It should not bother other bits and parts on the page.
but, DO keep in mind the following:
While a update panel does prevent a page re-fresh, it DOES DO A post-back, or better said what we call a PARTICAL post back.
that means on each timer click, the web page LOAD event WILL fire each time. So, just like clicking any button on the form, you do get a post-back, and page load event will trigger each time.
What this means?
Well, if you load up say a drop down list, or other controls say like some grid view?
You BETTER make sure that the page load event ONLY loads up that grid, or drop down ON THE REAL first page load - since page load always will trigger over and over.
So, say we drop in this div to the page - (your example - stripped down).
<asp:UpdatePanel ID="TimerUpdatePanel" runat="server"
UpdateMode="Conditional" ChildrenAsTriggers="true" >
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"
Enabled="false" />
<div style="width:20%;padding:15px;border:solid">
<h2 id="Timer_Time" runat="server">00:00:00</h2>
<h2 id="Timer_Day" runat="server">-------</h2>
<h2 id="Timer_Date" runat="server">00-00-0000</h2>
<hr />
<span id="PunchMsg" runat="server"></span>
<span id="TimerOption" runat="server" > </span>
<h2 id="stopWatch" runat="server" >
<span id="Hours" runat="server" >00:00:00</span>
</h2>
<asp:Button ID="PunchIN" Text="Punch In" runat="server" Visible="true"
style="float:left"
CssClass="btn btn-primary" OnClick="PunchIN_Click" >
</asp:Button>
<asp:Button ID="PunchOut" Text="Punch Out" runat="server" Visible="false"
style="float:right"
CssClass="btn btn-warning" OnClick="PunchOut_Click">
</asp:Button>
<br />
<br />
</div>
</ContentTemplate>
</asp:UpdatePanel>
And for code behind? Well, just like a date? We don't have to +1 to month etc.. ALL we need is the staring time when you punch in. From that we can get the elapsted time. We don't even need a timer here, and we could say update every 5 seconds, 10 seconds - it just don't matter.
So, our code can look like this now:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Call Update
End Sub
Sub Update()
Dim dtNow As DateTime = DateTime.Now
Timer_Day.InnerText = dtNow.ToString("dddd")
Timer_Date.InnerText = dtNow.ToString("dd-MM-yyyy")
Timer_Time.InnerText = dtNow.ToString("H:mm tt")
' now show elapsed time
Dim dtPunchIn As DateTime = Session("PunchIn")
Dim MyTimeSpan As TimeSpan = (dtNow - dtPunchIn)
Hours.InnerText = MyTimeSpan.ToString("hh\:mm\:ss")
End Sub
Protected Sub PunchIN_Click(sender As Object, e As EventArgs) Handles PunchIN.Click
Session("PunchIn") = DateTime.Now
Timer1.Enabled = True
PunchIN.Visible = False
PunchOut.Visible = True
End Sub
Protected Sub PunchOut_Click(sender As Object, e As EventArgs) Handles PunchOut.Click
Timer1.Enabled = False
Call Update()
PunchOut.Visible = False
PunchIN.Visible = True
Session("PunchIn") = Nothing
End Sub
And now we see this:
Hit punch in, and we now have this:
Ok, so at this point, assuming our page load event does not mess things up?
Then your other controls - such as drop down etc. should not matter - not one bit.
(but, if you re-load combo box on each page load - then you have big issue).
So, lets drop in two more "div" and while they do NOT need to be up-date panels,
we can and will mmake them as such (in a bit!!!).
The 2nd panel will be some filter options, and the 3rd panel will be a grid that 2nd panel can filter.
So, we drop in this filter panel. (float left next to punch in panel)
<div style="width:20%;padding:15px;border:solid 1px;float:left;margin-left:20px">
<h3>Panel 2</h3>
<h4>Filters</h4>
<div style="float:left">
<asp:Label ID="Label1" runat="server" Text="Select City"></asp:Label>
<br />
<asp:DropDownList ID="cboCity" runat="server" Width="160px"
DataValueField="City"
DataTextField="City" >
</asp:DropDownList>
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="Label2" runat="server" Text="Select Province"></asp:Label>
<br />
<asp:DropDownList ID="cboProvince" runat="server" Width="160px"
DataValueField="Province"
DataTextField="Province" >
</asp:DropDownList>
</div>
<div style="clear:both"></div>
<br />
<div style="float:left">
<asp:Label ID="Label3" runat="server" Text="Must Have Description"></asp:Label>
<br />
<asp:CheckBox ID="chkDescripiton" runat="server" />
</div>
<div style="float:left;margin-left:20px">
<asp:Label ID="Label4" runat="server" Text="Show only Active Hotels"></asp:Label>
<br />
<asp:CheckBox ID="chkActiveOnly" runat="server" />
</div>
<div style="clear:both"></div>
<br />
<div style="float:left;">
<asp:Button ID="cmdSearch" runat="server" Text="Search" CssClass="btn"/>
</div>
<div style="float:right;">
<asp:Button ID="cmdClear" runat="server" Text="Clear Fitler" CssClass="btn"/>
</div>
</div>
And then our grid view: (panel 3)
<div style="width:40%;padding:15px;border:solid 1px;float:left;margin-left:20px">
<h3>Panel 3</h3>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table" Width="60%">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Active" HeaderText="Active" />
</Columns>
</asp:GridView>
</div>
Code to load?
This:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData
End If
End Sub
Sub LoadData()
' load combo box for filters
Dim cmdSQL As New _
SqlCommand("SELECT City FROM tblHotels WHERE City is not null GROUP by City")
cboCity.DataSource = MyrstP(cmdSQL)
cboCity.DataBind()
cboCity.Items.Insert(0, New ListItem("All", "All"))
cmdSQL.CommandText =
"SELECT Province FROM tblHotels WHERE Province is not null GROUP by Province"
cboProvince.DataSource = MyrstP(cmdSQL)
cboProvince.DataBind()
cboProvince.Items.Insert(0, New ListItem("All", "All"))
' load grid data
cmdSQL.CommandText = "SELECT * FROM tblHotelsA ORDER BY HotelName"
GridView1.DataSource = MyrstP(cmdSQL)
GridView1.DataBind()
End Sub
NOTE SUPER care, we test/check IsPostBack = false - else our loading code will trigger each time. ALL YOUR web pages need this IsPostBack test on page load - even if no update panel. (your page will not work correctly if you don't add the above stub).
So, now we have this:
So, really, the combo boxes etc. in that 2nd panel (which is not yet a panel) does not really matter.
but, I could have any post-back from panel 2, say update panel 3. I don't really need to do this, but I could.
So, if I wrap a update panel around 2 and 3 above?
Then for 2nd panel (filter), I need to trigger update of panel 3
So, I add this to panel 2
<Triggers>
<asp:PostBackTrigger ControlID="cmdSearch" />
</Triggers>
but, all in all? use of combo boxes etc on your page? Should not matter.
But then again, every other day - we see posts here in that on page load event, they are re-loading drop downs, grids etc., and THEY REALLY only need to run and load on FIRST page load. As noted, failure to include the If NOt IsPostback code block will break most pages - even without a update panel.
But, do keep in mind, that page load WILL trigger on any post-back from a update panel - including button clicks, and the timer event. While the post-back is not a full page re-fresh, it does trigger page load each time.

Set focus on selected checkbox list item

I am trying to achieve a search function for a checkbox list that i have. Upon typing in the search text, it will set focus on the item in the checkbox list (preferably not through JavaScript).
Below is what i have for the design source.
<asp:Panel runat="server" DefaultButton="Button1">
<br />
<asp:TextBox ID="txtSearchCountry" runat="server" class="form-control" placeholder="Search for a country"/>
<asp:Button ID="Button1" runat="server" Style="display: none" OnClick="Button1_Click1" />
<br />
<div style="OVERFLOW-Y:scroll; WIDTH:100%; HEIGHT:115px">
<asp:CheckBoxList ID="chkCountry" runat="server" RepeatLayout="Table" Height="35px" class="form-control"></asp:CheckBoxList>
</div>
Followed by my vb code.
Protected Sub Button1_Click1(sender As Object, e As EventArgs)
Dim i As Integer
For i = 0 To chkCountry.Items.Count - 1
If InStr(chkCountry.Items(i).Value.Trim(), txtSearchCountry.Text.Trim()) = True Then
End If
Next
End Sub
With the code, i am able to find and match the search text. However, how am i able to set the focus to the item in the checkbox list?

Can't find a control in repeateritem.findcontrol

I have a nested repeaters in a form and bind them to tables in a dataset. I can find the controls by name and read and set values in the Itemdatabound event, However I can't find the control by the same name in a button click event. I can find the repeater and the item.
<asp:Repeater ID="rptrDivision" OnItemDataBound="rptrDivision_ItemDataBound" runat="server">
<itemtemplate>
<div class="fluid">
<div class="widget grid12">
<div class="whead"><div class="grid2"><h4 class="fieldDivision" >
<h4 class="fieldDivision" ><asp:Label ID="lblDivName" runat="server" Visible="True" ><%# DataBinder.Eval(Container.DataItem, "LocationName")%></asp:Label></h4></div>
<div class="grid10">
<div class="grid4 divAdmin" ><label><strong>Division Administrator: </strong> </label></div>
<div class="grid8 on_off">
<div class="floatL ml10"><asp:CheckBox ID="cbxDivMgr" name="chbox" runat="server" /></div>
</div>
</div></div>
<asp:Repeater ID="rptrCamera" OnItemDataBound="rptrCamera_ItemDataBound" runat="server" datasource='<%# Container.DataItem.Row.GetChildRows("CameraJoin")%>'>
<HeaderTemplate>
<div class="body">
</HeaderTemplate>
<itemtemplate>
<div class="formRow">
<div class="grid2">
<asp:Label ID="CameraName" runat="server" ><strong><%# Container.DataItem("Name")%></strong></asp:Label> </div>
<div class="grid10" >
<asp:RadioButtonList ID="rblRoles" runat="server" CssClass="mr10" RepeatColumns="5" CellPadding="2" CellSpacing="2">
<asp:ListItem Value="role1" >Role1</asp:ListItem>
<asp:ListItem Value="role2">Role2 </asp:ListItem>
<asp:ListItem Value="role3" >Role3 </asp:ListItem>
<asp:ListItem Value="Role4">role4 </asp:ListItem>
<asp:ListItem Value="none" Selected="True">N/A </asp:ListItem>
</asp:RadioButtonList>
</div>
</div>
</itemtemplate>
<FooterTemplate>
</div>
</FooterTemplate>
</asp:Repeater>
</itemtemplate>
</asp:Repeater>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="buttonM bBlue" OnClientClick="btnSubmit_Click" /> <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="buttonM bBlue" OnClientClick="btnCancel_Click"/>
The submit button is outside the repeater but in the same form
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
For Each Item As RepeaterItem In rptrDivision.Items
If (Item.ItemType = ListItemType.Item) Or (Item.ItemType = ListItemType.AlternatingItem) Then
DivLabel = CType(Item.FindControl("lblDivName"), Label)
DivName = DivLabel.Text
DivMgr = CType(Item.FindControl("cbxDivMgr"), CheckBox)
'''do some logic
End If
Next
End Sub
I've looked in the debugger and item has the correct number of controls so I know I am in the right place, but the findcontrol in the repeater item can't locate the control by name. It always comes back as null.
Every example I can find from here to MSDN forums to asp.net to bytes.com show looping through the items in the repeater and calling the find control the same way. I can't figure out what I am doing wrong.
Edit:
SO here is the kicker just make sure I'm not crazy I did a loop through the controlscollection on the repeater item and on the second control it comes back with the ID "lblDivName" yet if I call the item.findControl("lblDivName") it returns a null value.
Control events (like a Button's click event) occur before DataBound events (see ASP.NET Page Life Cycle on MSDN for more information). Thus, your Repeater is not DataBound yet, so its databound controls have not been initialized (they are null).
You have some options.
Preferably, you would use the Repeater's databound event to work with it's data items - since this is when you know for sure that they are initialized and populated with values.
However, you could just call "DataBind" prior to doing the processing in your Click event:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
rptrDivision.DataSource = yourDataSource
rptrDivision.DataBind()
For Each Item As RepeaterItem In rptrDivision.Items
' The rest of your code
End Sub
This should ensure that your controls have values.

Using multiple UpdatePanels on a single page without interfering with each other

It seems that when multiple UpdatePanels are on a single page, anytime an asyncPostBack occurs on one, all others will have their html reloaded. Is there a way around this?
Example
Example.aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div style="border: 1px solid black;">
<asp:TextBox runat="server" ID="txtTEST1" />
<asp:Label runat="server" ID="lblTEST1" />
<asp:Button runat="server" ID="btnTEST1" Text="AsyncPostBack1" />
<div onclick="this.innerHTML='Wooo!'">Click Me - UpdatePanel1</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div onclick="this.innerHTML='Wooo!'" style="padding: 1em;">Click Me. I'm not part of an Update Panel</div>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div style="border: 1px solid black;">
<asp:TextBox runat="server" ID="TextBox1" />
<asp:Label runat="server" ID="Label1" />
<asp:Button runat="server" ID="Button1" Text="AsyncPostBack2" />
<div onclick="this.innerHTML='Wooo!'">Click Me - UpdatePanel2</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Example.aspx.vb
Protected Sub btnTEST1_Click(sender As Object, e As EventArgs) Handles btnTEST1.Click
lblTEST1.Text = "Refreshed at " & DateTime.Now.ToString()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = "Refreshed at " & DateTime.Now.ToString()
End Sub
Testing the issue
Click on all 3 of the divs with the "Click Me" text so that HTML is altered inside and outside of the UpdatePanels.
Click one of the buttons labeled "AsyncPostBack". Regardless on which one is clicked, both UpdatePanels will have their HTML rerendered and replaced, as seen by the 2 divs inside the UpdatePanels resetting to their original text.
So I ask, is it possible to have multiple UpdatePanels on the same page that don't cause each other to rerender every time one of them has a asyncPostBack event.
yes
set updatemode=conditional
provide the triggers which will trigger the update. here is a link to an example. (#1 result on google) http://ajax.net-tutorials.com/controls/updatepanel-control/
Try adding mode to update panel tag. If mode is not give the default mode is always. If the UpdateMode property is Always, the UpdatePanel control's content is updated on every postback that originates from anywhere on the page. Microsoft documentation about UpdateMode
<asp:UpdatePanel ID="BugsListUpdatePanel" runat="server" UpdateMode="Conditional">

ASP.NET: OnChange on Dynamically Created Textbox inside UpdatePanel Fires Twice

Pretty basic set-up. I'm creating a number of textboxes, all calling a function during the onchange event to update their value to the database. These boxes are dynamically created in the backend because the data changes based on specific criteria that can be changed on the page. Here's the creation of the boxes:
Dim t as TableRow
tC = New TableCell
Dim txtBox As New TextBox
txtBox.ID = "SampleTextBox" & counter
txtBox.Text = dt.Rows(i)(11).ToString
txtBox.ClientIDMode = UI.ClientIDMode.Static
txtBox.Attributes.Add("onchange", "return UpdateLabTestValue('" & txtBox.ClientID & "');")
tC.CssClass = "padBoth"
tC.Controls.Add(txtBox)
t.Cells.Add(tC)
tblResults.Rows.Add(t)
On the HTML side of the ball:
<asp:UpdatePanel ID="uplResults" runat="server">
<ContentTemplate>
<div class="formContentLeft">
<fieldset class="collapsible" style="width: 90%;">
<legend>Results</legend>
<div class="formContentLeft">
<div class="formField">
<span class="formInline">Status: </span><span class="formInput">
<asp:DropDownList ID="dlStatus" runat="server" /></span>
</div>
</div>
<br />
<br />
<asp:Table ID="tblResults" runat="server" />
<div class="centeredButtonRow">
<asp:Button ID="btnSaveResults" runat="server" Text="Save" />
</div>
<asp:Label ID="errorMessage" runat="server" CssClass="errorMessage" />
</fieldset>
</div>
</ContentTemplate>
</asp:UpdatePanel>
When I enter a number into the Textbox, the event fires as expected, but it fires twice. Any thoughts?
Changed this to an "onblur" and it works. There must be something else causing the fire for the change, although the same textbox is firing it off twice. In any case, I resolved this by switching to onblur.

Resources