Introduction
In this article I will explain how to bind GridView using Class and Property Here I am using Class and Property if you have any problem with this read OOP Concepts first.
Description
First we need a database design means a database and a table in which we perform our select operation. So here is my Database Design:
create database User
Use User
create table UserInformation( UserId int, UserName varchar(50), Location varchar(50))
Insert records according to your need and after this design Class in C# in behalf of table structure.
In Asp.Net WebApp Application goto solution Explorer, click on add and select Class, Named it same as table name in database(Just for better understanding) .
public class UserInformation
{
string _userId;
public string USerId
{
get
{
return _userId;
}
set
{
_userId = value;
}
}
string _userName;
public string UserName
{
get
{
return _userName;
}
set
{
_userName = value;
}
}
string _location;
public string Location
{
get
{
return _location;
}
set
{
_location = value;
}
}
}
Aspx Page Design
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns = "false"
AllowPaging = "true" OnPageIndexChanging = "OnPaging">
<Columns>
<asp:BoundField DataField = "UserId" HeaderText = "User
Id" />
<asp:BoundField DataField = "UserName" HeaderText = "User
Name" />
<asp:BoundField DataField = "Location" HeaderText = "Address" />
</Columns>
</asp:GridView>
Code Behind (.cs )Page Code
Here i Get UserInformation type of data from Databse and store it and return all users. If you are not comfortable with List please read about List first. and for using List you have to add a Collection namespace on top.
private List<UserInformation> GetData()
{
using (SqlConnection con = new SqlConnection("Data Source=JP;Initial Catalog=User;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM UserInformation", con))
{
con.Open();
using (SqlDataReader sdr =
cmd.ExecuteReader())
{
List<UserInformation> users
= new List< UserInformation >();
while (sdr.Read())
{
users.Add(new Customer());
users[users.Count
- 1].UserId = sdr["UserID"].ToString();
users[users.Count
- 1].UserName = sdr["UserName"].ToString();
users[users.Count
- 1].Location = sdr["Location"].ToString();
}
con.Close();
return users;
}
}
}
}
Now bind grid from users return by GetData Method.
private void BindGrid(List<UserInformation> users)
{
gvUser.DataSource = users;
gvUser.DataBind();
}
for to display records in grid on localhost ,call this method on PageLoad.I write my BindGrid code with in IsPostBack. It means my GridView only binds when firstTime page loaded.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid(this.GetData());
}
}
0 comments:
Post a Comment