This article will show
you how you can bind a class property list to a gridview control using c#.net
using asp.net.
Some on my previous
articles are as follows: Gridview
Auto Generate Row Number In Asp.Net Using C#.Net, Bind
TextBox Control Inside TemplateField Of GridView Using C#.Net In Asp.Net, Export
GridView Or Table Data Into PDF By C#.Net In Asp.Net Using jQuery, Reading
XML Document in C# Using Linq and Bind To GridView In Asp.Net, How
to Find Gridview Control on Button Click in Asp.Net C#, Nested
GridView Using c#.Net In Asp.Net, Read
XML File in Dataset And Bind To GridView In Asp.Net Using C#.Net.
So for this article
first we will create a new asp.net application and add class file into the
project. Here is the sample code into class file.
public class CountryDetail
{
public int Id { get; set; }
public string CountryName { get; set; }
public string Population { get; set; }
public string Code { get; set; }
}
|
After this we will add
the below code of gridview into the page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication7.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Class
Property to GeidView Using C#.net In Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="CountryName"
HeaderText="Country Name"
/>
<asp:BoundField DataField="Population"
HeaderText="Population"
/>
<asp:BoundField DataField="Code" HeaderText="Code" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
|
In above
code I have bound the property of the class to the gridview. Now check the code
to bind the data to gridview.
using System;
using
System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<CountryDetail>
countryDetail = new List<CountryDetail>();
countryDetail = GetCountryData();
GridView1.DataSource = countryDetail;
GridView1.DataBind();
}
private List<CountryDetail>
GetCountryData()
{
List<CountryDetail>
countryDetail = new List<CountryDetail>();
countryDetail.Add(new CountryDetail { Id = 1, CountryName = "India", Code = "IN", Population = "125Cr" });
countryDetail.Add(new CountryDetail { Id = 2, CountryName = "Pakistan", Code = "PK", Population = "50Cr" });
countryDetail.Add(new CountryDetail { Id = 3, CountryName = "America", Code = "US", Population = "24Cr" });
return countryDetail;
}
}
|
In above
code I have prepared the list of record. On page load I have assign the value
to the gridview control to display the record into the gridview. Now we have
done run the application to check the output.
0 comments:
Please let me know your view