如何从数据列表中获取ID? [英] How to get the id from datalist ?
问题描述
我有包含项目的数据列表
在每个项目下都有一个链接
I have datalist which has items
and under every item there is a link
<asp:LinkButton runat="server" ID="Add" OnClick="lnkAdd_Click"
Text="Add to cart" CommandName="Add" />
我为此链接创建事件处理程序
I make event handler for this link like that
protected void lnkAdd_Click(object sender, EventArgs e)
{
// int ProId =Convert.ToInt32(((Label)ListView_Products.Controls[0].FindControl("IDLabel")).Text);
int ProductID = int.Parse("ItemID");
AddToShoppingCart(ProductID);
Response.Redirect("ShoppingCartaspx.aspx");
}
我的问题
如何从数据列表中获取productID?
它给我错误null引用
在此先感谢.
my question
how to get productID from datalist ???
it gives me error null reference
thanks in advance .
推荐答案
尝试:
以下将ItemID绑定到LinkButton的CommandArgument.
Try:
Following binds the ItemID to the CommandArgument of the LinkButton.
<asp:LinkButton ID="LinkButton1" runat="server" Text="Add to cart"
OnClick="LinkButton1_Click" CommandArgument='<%# Eval("ItemID") %>' />
然后,您可以在后面的代码中像这样检索它:
You can then retrieve it like this in the code behind:
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton myButton = sender as LinkButton;
if (myButton != null)
{
int id = Convert.ToInt32(myButton.CommandArgument);
}
}
发送方持有对触发事件处理程序的LinkButton的引用.
您可以将对象转换为LinkButton,然后检索其CommandArgument并将其转换为int.
The sender holds a reference to the LinkButton that triggered the event handler.
You can cast the object into a LinkButton and then retrieve its CommandArgument and cast that into an int.
使用此语法
Use This Syntax
DataListItem dl = ((DataListItem)(DataControlFieldCell(((ImageButton)sender).Parent).Parent));
Int32 var = Convert.Toint32(((Label)dl.FindControl("lbl")).ToString());
如果许多产品并且想要启用多选功能,那么只需在for循环中使用下面的代码即可.
If you have many products and want to make multi-selection enable, then just use below code inside for loop.
Label lblID = (Label)DList1.Items[i].FindControl("IDLabel");
Int32 PID = Convert.ToInt32(lblID.ToString();
唯一的不同是
如有疑问,请回复.
约翰·巴特(John Bhatt),
P.Yar.B Complex
Only Difference is that
Reply if some confusion.
John Bhatt,
P.Yar.B Complex
这篇关于如何从数据列表中获取ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!