This code sample Binds an ObjectArray to GridView and to add columns dynamically
To Test this code, you need a webpage with a GridView named "GridView1" Set its AutoGenerateColumns property to "false"
In Page Load event add the following code
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { SetupGrid(); } }
The following method Adds columns and Binds Data to Gridview
private void SetupGrid() { BoundField idField = new BoundField(); idField.DataField = "ID"; idField.HeaderText = "ID"; GridView1.Columns.Add(idField);
BoundField nameField = new BoundField(); nameField.DataField = "Name"; nameField.HeaderText = "Name"; GridView1.Columns.Add(nameField);
ButtonField btnField = new ButtonField(); btnField.ButtonType = ButtonType.Button; btnField.Text = "Select"; btnField.CommandName = "Select"; GridView1.Columns.Add(btnField);
List emps = new List(); emps.Add(new Employee(1, "Sabu")); emps.Add(new Employee(2, "Mathew")); emps.Add(new Employee(3, "Edwin")); emps.Add(new Employee(4, "Alex")); emps.Add(new Employee(5, "John")); emps.Add(new Employee(6, "Ann")); GridView1.DataSource = emps; GridView1.DataBind(); }
Employee class's code is given below
public class Employee { private int _ID = 0;
public int ID { get { return _ID; } set { _ID = value; } } private String _Name = "Sabu";
public String Name { get { return _Name; } set { _Name = value; } }
public Employee(int id, string name) { ID = id; Name = name; } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|