Search code examples
c#sqlasp.netlistboxlinkbutton

ASP.NET Populate a listbox without a postback


I have a simple aspx page with a textbox, linkbutton and listbox.

The listbox is to be populated with values from a stored procedure in a SQL database.

What I'd like to do, somehow, is to populate the listbox with those variables when the user clicks the linkbutton. Ideally, I'd like to do this WITHOUT a postback.

Is there any way this can be accomplished?

Thanks,

Jason


Solution

  • I mocked one up for you really quickly.

    <form id="form1" runat="server">
    
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    
    <div>
    
    
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
                <br />
                <asp:ListBox ID="ListBox1" runat="server" DataTextField="yourdesiredcolumnamegoeshere"></asp:ListBox>
            </ContentTemplate>
        </asp:UpdatePanel>
    
    </div>
    
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
        ConnectionString="Data Source=;Initial Catalog=;User ID=;password=" 
        ProviderName="System.Data.SqlClient" 
        SelectCommand="SELECT [yourdesiredcolumnamegoeshere] FROM [yourtablenamegoeshere]">
    </asp:SqlDataSource>
    </form>
    

    On the code behind:

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ListBox1.DataSource = SqlDataSource2;
        ListBox1.DataBind();
    }
    

    Of course you would change the SqlDataSource to your stored proc, but when you clicked the button, it would populate that list without a postback. Let me know if you need anything else.

    -JJ