Bind Gridview in Asp.net Using Generic
Bind Gridview in Asp.net Using Generic
for Binding Gridview in asp.net using Generic,You have to be
create a Class.
The class mainly define the column of your Database table.
Step 1 :DataBase Design :
Table Creation.
CREATE TABLE [dbo].[GridView](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NULL,
[age] [int] NULL,
[salary] [decimal](18, 0) NULL,
[country] [varchar](50) NULL,
[city] [varchar](50) NULL,
CONSTRAINT [PK_GridView] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Step 2: Create .cs Class of your Database table,Here I am using it with name “Gridview”.
Add a new class by adding
a new Item.
Write this code inside it.
public class gridview
{
public string name { get; set; }
public int age { get; set; }
public int salary { get; set; }
public string country { get; set; }
public string city { get; set; }
}
Step 3: Design Web Page.
<form id="form1" runat="server">
<div>
<asp:GridView ID="gr" runat="server"></asp:GridView>
</div>
</form>
Step 3: Write Logic
on .CS Page.
List<gridview> gvp = new List<gridview>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["KANDY"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
bindgridview();
}
//Gridview
Bind Function.
public void bindgridview()
{
// gvp =
bindgr();
gr.DataSource = bindgr();
gr.DataBind();
}
protected List<gridview> bindgr()
{
DataTable dt = new DataTable();
string qu = "select
top(5) * from gridview";
SqlDataAdapter ad = new SqlDataAdapter(qu, con);
con.Open();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
gridview gv = new gridview();
gv.name = dt.Rows[i]["name"].ToString();
gv.age =Convert.ToInt32(dt.Rows[i]["age"]);
gv.salary =Convert.ToInt32(dt.Rows[i]["salary"]);
gv.country = dt.Rows[i]["country"].ToString();
gv.city = dt.Rows[i]["city"].ToString();
gvp.Add(gv);
}
}
return gvp;
}
Comments
Post a Comment