Click to See Complete Forum and Search --> : How to create a second button inside DataList control and its C# code


paradise_wolf
10-02-2006, 07:31 PM
I have a button ( add to cart ) inside a DataList control but I need to add an additional button ( buy now ) and its event handler but I do not know how to do that because probably I can’t use the same “CommandArgument” twice.

Here is the relevant code:

~~~~~~~~~~~~~~~~~~~~
<asp:DataList ID="promotionlist" Runat="server" OnItemCommand="promotionlist_ItemCommand" >
<ItemTemplate>

<asp:ImageButton ID="AddToCart" ImageUrl="~/Images/addtocart.gif" CommandArgument='<%# Eval("ProductID") %>' runat="server" />

<asp:ImageButton ID="BuyNow" ImageUrl="~/Images/buynow.gif" CommandArgument='<%# Eval("ProductID")%>' runat="server" />

..

</ItemTemplate>
</asp:DataList>
~~~~~~~~~~~~~~~~~~~~

C# code:
~~~~~~~~~~~~~~~~~~~~
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
promotionlist.DataSource = CatalogAccess.GetProductsOnPromotion();
promotionlist.DataBind();
}
}

protected void promotionlist_ItemCommand(object source, DataListCommandEventArgs e)
{

string productId = e.CommandArgument.ToString();
ShoppingCartAccess.AddItem(ProductId);


}
~~~~~~~~~~~~~~~~~~~~

sirpelidor
10-03-2006, 04:40 PM
the update, cancel, and update buttons were pre-written by the datalist control. (think of datalist control is just another custom control written by somebody...)

if you want to add the second button (lets call "myBtn"), you'll have to manually add to your control and code-behind....

step 1) put your control in your item template or edit template or both (depends on where u want that button shows)


<asp:Button CommandName="myBtn" Text="my button" Runat="server" ID="myBtn" NAME="myBtn" />


step 2) now, you'll need to manually register your event and wire to a method... (suppose your datalist is call "myDataList")

private void Page_Load(object sender, System.EventArgs e){
System.Web.UI.WebControls.Button btn;
//find that button and point it to your btn variable...
for(int i = 0; i < this.myDataList.Items.Count - 1; i++){
btn = (System.Web.UI.WebControls.Button)this.myDataList.Items[i].FindControl("myBtn");
//in case if it couldn't find the button....
if(btn != null) btn.Click +=new EventHandler(btn_Click);
}//end for
}//end load


step 3) now we make a method call "btn_click", and tell ASP.NET what to do when button is clicked...

private void btn_Click(object sender, EventArgs e){
Response.Write("Hello myButton clicked!");
}//end btn_Click