Bind an ArrayList with Hyperlinks to a GridView

A very frequently asked question in the forums is that of binding an ArrayList with Hyperlinks to an ASP.NET GridView control. Here's how to do so:

Declare a GridView in the following manner:


    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">


    <Columns>


    <asp:HyperLinkField DataNavigateUrlFields="Text" DataTextField="Value" />


    </Columns>


    </asp:GridView>




Notice that we have declared a <asp:Hyperlink> field and set the DataNavigateUrlFields to "Text" and the DataTextFields set to "Value". The AutoGenerateColumns property of the GridView is set to False.

Now add the following code that binds the ArrayList with Hyperlinks to the GridView

C#


        ArrayList aList = new ArrayList();


        aList.Add(new ListItem("http://www.asp.net"));


        aList.Add(new ListItem("http://www.microsoft.com"));       


        aList.Add(new ListItem("http://www.dotnetcurry.com"));


        aList.Add(new ListItem("http://www.devcurry.com"));


        GridView1.DataSource = aList;


        GridView1.DataBind();




VB.NET


        Dim aList As New ArrayList()


        aList.Add(New ListItem("http://www.asp.net"))


        aList.Add(New ListItem("http://www.microsoft.com"))


        aList.Add(New ListItem("http://www.dotnetcurry.com"))


        aList.Add(New ListItem("http://www.devcurry.com"))


        GridView1.DataSource = aList


        GridView1.DataBind()







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: