Friday, February 29, 2008

ASP.Net DataList HyperLink Template

Having seen the basics of DataList in http://shalvinpd.blogspot.com/2008/02/aspnet-datalist.html, lets take up a bit more complex DataList application.


We are going to implement a multiform one to many application similar to what you see in Ecommerce application. In the first page there might be a list of categories. All Categories will be appearing as hyperlinks. On clicking a Category you will taken to the the child page say SubCategory.





So we have to produce hyperlink templates. I am not going into the details of database connectivity and the like (You can refer http://shalvinpd.blogspot.com/2008/02/aspnet-datalist.html for basics of DataList) instead I am straight a way jumping into DataList ItemTemplate.




//Default.aspx








Here we are specifying an html anchor tag as passing the CatId as Query String to the next page.
In the second page we can extract the QueryString value pass it into the select statements where clause and display the result.


<Columns>
    <asp:TemplateField>
                <ItemTemplate>
                       
                    <a href = '<%#  String.Format("Cat.aspx?CatId={0}", Eval("CategoryId")) %>'>
                        <%# Eval("CategoryName") %>
                    </a>
                </ItemTemplate>
            </asp:TemplateField>
</Columns>


GridView is also having the equivalent functionality.



create procedure spGetSubCats(@pCatId int)
as
select * from SubCategory where CatId = @pCatId
go




//SubCata.aspx.cs


using System.Data.SqlClient;
public partial class SubCat : System.Web.UI.Page
{
SqlConnection cnn;
SqlDataAdapter da;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
cnn = new SqlConnection(ConfigurationManager.AppSettings.Get("Cnn"));
cnn.Open();
da = new SqlDataAdapter("spGetSubCats " + Convert.ToInt32(Request.QueryString["CatId"]), cnn);
da.Fill(ds, "SubCat");
dlstSubCat.DataSource = ds.Tables["SubCat"];
DataBind();
}
}

//SubCat.aspx









Happy Programming
shalvinpd.blogspot.com

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete