简体   繁体   中英

Create gridview with SQL query when button is clicked?

I am extremely new to ASP.NET and trying to build a basic page in C# for use at work. It basically consists of an execute button that should trigger a query from an external SQL server and display it in a gridview object.

Currently the gridview & query will run on pageload, however as the query can take 2-3 minutes to return (often causing a timeout) I'd rather run the query when a button is clicked.

I imagine the best way is to use it in code behind but am not having any luck with any info found online/in other questions. All the gridview/query is currently in the page directly as below: (SQL has been reduced for example)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RecId" DataSourceID="SQLDB01" CellPadding="4" CellSpacing="3" ForeColor="#333333" GridLines="Horizontal" Width="60%">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="Unit" HeaderText="Scanner" SortExpression="Scanner" />
            <asp:BoundField DataField="Location" HeaderText="PortNo" SortExpression="PortNo" />
            <asp:BoundField DataField="EventDate" HeaderText="EventDate" SortExpression="EventDate" />
        </Columns>
        </asp:GridView>

        <asp:SqlDataSource ID="SQLDB01" runat="server" ConnectionString="<%$ ConnectionStrings:services_dbConnectionString %>" SelectCommand="SELECT TOP 20 * FROM dbo.Event ORDER BY RecId DESC"></asp:SqlDataSource>

How do I a) get the button to trigger all this instead, and b) move it all into code behind if needed?

If you click on Design tab under your programming window in visual studio, you can see a visual representation of your button. Double clicking on this will automatically create a click Method for that button in your .cs file. You can write code to populate the button from the database inside that Method. You will need to write it in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM