Wednesday, March 26, 2008

Using GridView with Custom Collection

I had a requirement of displaying an objct collection returned by a web service. It took a bit of time to understand and display this data in a GridView.

The following gives example of using the grid view in your code. It is using array of MyObject to display information.

1) To display custom columns, add the following code and add the columns from the gridview->properties->columns. Add the first field which will be clicked as buttonField with ButtonType under Appearance group as link. Also select CommanName under Behaviour group as Select. Unless you set it, SelectedIndexChanged event will not fire and RowCommand event should be captured.
2) Add subsequent columns to be shown as BoundField
3) Handle SelectedIndexChanged to handle clicking of a particular row. GridView1.SelectedIndex will give the index of the row clicked. This index into the myAr will give the object details.

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyObject[] myAr = new MyObject[] { new MyObject("1", "1.1"), new MyObject("2", "2.1"), new MyObject("3", "3.3"), new MyObject("4", "4.4") };
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(new MyObject("1", "11"));
al.Add(new MyObject("2", "22"));
al.Add(new MyObject("3", "33"));
GridView1.DataSource = myAr;

GridView1.AutoGenerateColumns = false;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
}
}

public class MyObject
{
private string firstName;
private string lastName;

public MyObject(string fn, string ln)
{
FirstName = fn;
LastName = ln;
}

public string FirstName
{
get { return firstName; }
set { firstName = value; }
}

public string LastName
{
get { return lastName; }
set { lastName = value; }
}
}

GridView Code:
tags have been removed due to the blog writer tool:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="FirstName"
onrowcommand="GridView1_RowCommand"
onselectedindexchanged="GridView1_SelectedIndexChanged>
<columns>
<asp:ButtonField CommandName="select" DataTextField="FirstName"
HeaderText="FirstName" Text="Button" /<
<asp:boundfield datafield="LastName" headertext="Lastname"<
</columns<
</asp:GridView>

1 comment:

Unknown said...

In this article you mentioned how we use the Grid view.Here you mentioned some examples also.But after all the things it creates confusion.Some loop holes are there which doesn't clear all the aspects.
digital signature Adobe