Description: a GridView is a databound control for displaying and manipulating data in a web application. A GridView displays data in tabular format, in ohter words a collection of rows and columns. Here each row represents one record, each column represents one field in the database table.
Here I would like to bind the data to Griview using SqlDatasource.
SqlDataSource
- SqlDataSource is a Web server control, it allows you to access the data from any relational database. It can be accessed from Microsoft SQL Server and Oracle databases. As well as we have OLEDB and ODBCDataSources also.
- You can use this SqlDataSource with any databound control like GridView, formview, treeview and so on to display and manipulate the data in webpages with no or little code.
- In SqlDatasource you need to specify SQL queries or a Stored Procedure name to execute, then SqlDataSource internally uses respective ADO.NET classes to perform operations on the database.
Example to demonstrate the GridView with SQlDataSource:
Consider the following table Employee:
Set the ConnectionString in web.config.
- <connectionStrings>
- <add name="myconnection" connectionString="Data Source=ABHI-PC\SQLEXPRESS;Initial Catalog=Articles;Integrated Security=True"
- providerName="System.Data.SqlClient" />
- </connectionStrings>
Deault.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false"
- DataKeyNames="EmpId" DataSourceID="SqlDataSource1"
- HeaderStyle-BackColor="Green" AlternatingRowStyle-BackColor="LightPink"
- AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" >
- <Columns>
- <asp:BoundField HeaderText ="Employee Id" DataField="EmpId" />
- <asp:BoundField HeaderText="Employee Name" DataField="EmpName" />
- <asp:BoundField HeaderText="Employee EmailId" DataField="EmpEmailId" />
- <asp:BoundField HeaderText="Mobile Number" DataField="EmpMobileNum" />
-
- </Columns>
- </asp:GridView>
- <asp:SqlDataSource ID="SqlDataSource1" runat="server"
- ConnectionString="<%$ ConnectionStrings:myconnection %>"
- selectCommand="select * from employee"
- UpdateCommand="update employee set EmpName=@EmpName,EmpEmailId=@EmpEmailId,EmpMobileNum=@EmpMobileNum where EmpId=@EmpId"
- DeleteCommand="delete from employee where EmpId=@EmpId">
- </asp:SqlDataSource>
-
- </div>
- </form>
- </body>
- </html>