[英]get selected listview item row from database
我有一個綁定到數據庫的列表視圖:
//C# code
protected void Page_Load(object sender, EventArgs e)
{
DataSet1.ProductDataTable pTable = new ProductTableAdapter().GetDataByCategory();
productListview.DataSource = pTable.Rows;
productListview.DataBind();
}
當我單擊一個鏈接按鈕時,我想從該選定的數據庫行中獲取所有列。
//ASP.NET
<asp:Listview ID="productListview" runat="server" GroupItemCount="3">
<LayoutTemplate>
<table runat="server">
<tr>
<th colspan="3">PRODUCTS LIST</th>
</tr>
<tr runat="server" id="groupPlaceholder" />
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<td runat="server" id="itemPlaceholder" />
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<img src='<%# Eval("PicURL") %>' width="150" height="150"/><br />
<asp:LinkButton
ID="chosenLinkButton" runat="server"
CommandName="AddProduct"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'
Text='<%#Eval("ProductName") %>'><br />
<asp:Label ID="LinkButton1" runat="server" Text='<%#Eval("Price") %>'></asp:Label><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Size") %>'></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Description") %>'></asp:Label><br />
<asp:Label ID="Label3" runat="server" Text='<%#Eval("SalesQuantity") %>'></asp:Label>
</td>
</ItemTemplate>
</asp:Listview>
之后,我要獲取行值並將其放入稱為“ cartItems”的類中,其中具有諸如價格,名稱,描述之類的屬性,如下所示:
private string ProductName;
public string _ProductName
{
get { return ProductName; }
set
{
ProductName = value;
}
}
下面更新! 這確實起作用。 它確實從數據庫中獲取價格,我在做什么錯呢?
protected void productListview_ItemCommand(object sender, ListViewCommandEventArgs e)
{
//Made a adapter to database cause I thought I could get the selected talbe colums from here...
DataSet1.ProductDataTable productTable = new ProductTableAdapter().GetDataByCategory();
if (e.CommandName == "AddProduct")
{
//create a cartItem instance that contains ProductName, UnitPrice, type & decription
var currentPrimaryKey = Convert.ToInt32(e.CommandArgument);
CartItem chosenItem = new CartItem();
chosenItem.UnitPrice = (decimal)productTable.Columns.IndexOf("Price");
//how can I add the price from the database here?
}
}
將代碼連接到ListView上的ItemCommand事件
使用類似於以下代碼的鏈接;
<asp:LinkButton ID="lnkEdit" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'
CommandName="Select" > <%# Convert.ToString(Eval("Description")) %></asp:LinkButton>
foreach (DataSet1.ProductRow item in pTable.Rows)
{
//if the current item in the table is matching the item that is selected by the user
if (item.ID == Convert.ToInt32(e.CommandArgument))
{
//then assign values to a created instance of a cartItem (a class that I have)
CartItem currentItem = new CartItem();
currentItem.UnitPrice = item.Price;
}
}
結論:通過使用Convert.ToInt32()方法將對象轉換為整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.