How to get Datatables to load with button click.

How to get Datatables to load with button click.

rimshot609rimshot609 Posts: 9Questions: 6Answers: 0

I am using datatables with asp.net (c#) that's getting data from an SQL server. It works fine when my method is called from the page load event in c#. However, I don't want it to load when the page loads. I want the query to run when I click a button. How should I do this? I have tried executing javascript when button is clicked and then calling method but it doesn't load the style - just the table.
Thanks

 protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                
            }
            else
            {
                DataTable(); // I don't want to do this. I want it to populate when button is clicked, and it does, but the style is //missing!
            }
        }

public void DataTable()
        {
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("select * from [table]", con))
                    
                
                {
                    cmd.Parameters.AddWithValue("@AccountNumber", txtSearchKeyword.Text);
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        cmd.CommandType = CommandType.Text;
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        tblAccount.DataSource = dt;
                        tblAccount.DataBind();
                    }
                }
            }
        }

And here is my javascript:

$(function () {
    $('[id*=tblAccount]').prepend($("<thead></thead>").append($(this).find("tr:first"))).DataTable({
        "responsive": false,
        "sPaginationType": "full_numbers"
    });   

});

Front End:

                            <asp:GridView ID="tblAccount" runat="server" AutoGenerateColumns="false" CssClass="table-hover">
                                <Columns>
                                    <asp:BoundField DataField="CompanyName" HeaderText="Company Name" />
                                    <asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
                                    <asp:BoundField DataField="Address" HeaderText="Company Address" />
                                </Columns>
                            </asp:GridView>

Answers

  • allanallan Posts: 63,468Questions: 1Answers: 10,466 Site admin

    Have a look at my reply here. Its basically the same thing, but replace "Django" in that thread with ".NET"!

    The key is that you need to be able to get the server to respond with JSON data to an HTTP request. For that, you'll need to refer to the .NET documentation.

    Allan

This discussion has been closed.