Bind grid view using c#
Introduction
In this article i am going to write about gridview binding.
You can bind gridview from database very easy, let see the full code
Code
- First create database having name DemoDatabase
- Create table "Users" in DemoDatabase
- insert demo data in table users from script
- Execute following script in sql database.
CREATE DATABASE [DemoDatabase] CREATE TABLE [dbo].[Users]( [id] [int] IDENTITY(1,1) NOT NULL, [FirstName] [varchar](50) NULL, [LastName] [varchar](50) NULL, [UserName] [varchar](50) NULL, [Email] [nvarchar](150) NULL, [imageURL] [nvarchar](max) NULL ) INSERT [dbo].[Users] ( [FirstName], [LastName], [UserName], [Email] ) VALUES ( N'Nirav', N'Prabtani', N'Nills', N'niravjprabtani@gmail.com') INSERT [dbo].[Users] ( [FirstName], [LastName], [UserName], [Email] ) VALUES ( N'Rajan', N'Mrug', N'Raj', N'Raj@gmail.com') INSERT [dbo].[Users] ( [FirstName], [LastName], [UserName], [Email] ) VALUES ( N'Rajesh', N'Saradhara', N'Rajesh', N'rajesh@yahoo.in') INSERT [dbo].[Users] ( [FirstName], [LastName], [UserName], [Email] ) VALUES ( N'Dharmendra', N'Pansara', N'Dhamo', N'Dhamo@hotmail.com')
First of all we design gridview by simple drag and drop from datatools toolbar to page
1) GridDemo.aspx
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Asp.net Gridview Demo using c#</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="grdDemo" runat="server"> </asp:GridView> </div> </form> </body> </html>
2) GridDemo.aspx.cs
At code behind.. :)
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
public void BindGrid()
{
SqlConnection cn = new SqlConnection("Data Source=PC1-PC\\PC1SQL;Initial Catalog=DemoDatabase1;User ID=sa;Password=password_1");
SqlCommand cmd = new SqlCommand("Select * from Users", cn);
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtGetData = new DataTable();
da.Fill(dtGetData);
grdDemo.DataSource = dtGetData;
grdDemo.DataBind();
}
No comments :
Post a Comment