Loading data from SQL Server database tables into GridView using ASP.Net AJAX Server controls is quite similar to the normal way. The difference is placing the ASP.Net Server controls like GridView and Buttons inside the AJAX Extensions Server Control called UpdatePanel.
First of all drag and drop the ScriptManager on top of the ASP.Net web page to include JavaScript client libraries required for AJAX functionality. Then place an UpdateProgress Control to display the status message about the update progress. Next step is to place the UpdatePanel to hold the GridView Control to display the data, Label control to display the error or exception if occurred and button control to bind the GridView Data.
Here UpdatePanel Control enables the partial-page postback asynchronously to update the data of GridView placed inside it.
Double click on button control to generate the click event handler for Button control. Create a bindGridView function to connect and bind the SQL Database table data with GridView.
HTML Code for Placing the GridView Control in AJAX UpdatePanel
<form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"> <ProgressTemplate> <asp:Label ID="lblProgress" runat="server" Text="Loading . . . . . "></asp:Label> </ProgressTemplate> </asp:UpdateProgress> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> <asp:Label ID="lblErrorMsg" runat="server"></asp:Label> <asp:Button ID="btnLoadData" runat="server" Text="Fill GridView" OnClick="btnLoadData_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </form>
C# code to Load the GridView using AJAX Asynchronous Postback
protected void bindGridView() { string connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString(); SqlConnection sqlCon = new SqlConnection(connectionString);
try { SqlCommand sqlCmd = new SqlCommand("select * from categories", sqlCon); sqlCmd.CommandType = CommandType.Text; SqlDataAdapter sqlAdp = new SqlDataAdapter(sqlCmd); DataSet myDataSet = new DataSet(); sqlAdp.Fill(myDataSet);
// Delay the current Thread to display // the UpdateProgress status // Not required in real projects System.Threading.Thread.Sleep(4000);
GridView1.DataSource = myDataSet; GridView1.DataBind(); } catch(Exception ex) { lblErrorMsg.Text = ex.Message; } }
protected void btnLoadData_Click(object sender, EventArgs e) { bindGridView(); }
You can use the Northwind Database to test the sample code. Place your connection string inside the web.config ConnectionString section.
Be the first to rate this post
Tags: asp.net, ajax, ajax gridview loading, ajax updatepanel, ajax scriptmanager, ajax sample, ajax gridview sample, asp.net ajax extensions
8/23/2008 8:55:21 PM