BigRabbit BigRabbit - 1 year ago 106 Question

ASP.Net add item to listbox without posting

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">
<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 class="col-xs-6">
<asp:Button ID="btnRemoveEmp" runat="server" Text="Remove Emp" CssClass="btn btn-danger top-buffer" Width="100%" />

<asp:ListBox ID="listEmps" runat="server"
CssClass="top-buffer add-height"



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

'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

'add to list
End If

End If
End Sub

How can I properly add items to a listbox without refreshing the page?

Answer Source

Remove your If Not IsPostBack() Then check in your button click event. The PostBack 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.