我试图在事件中获取绑定到EditItemTemplate的数据值。 ListView id是lvProducts,如何在UpdateButton_Click方法中引用项目数据?
这是编辑项目模板:
<EditItemTemplate>
<tr>
<td class="narrow"><asp:Label runat="server" Text='<%#Bind("ProductID")%>' ID="idLabel"></asp:Label></td>
<td class="wide"><asp:Textbox runat="server" Text='<%#Bind("ProductTitle")%>' ID="nameEdit"></asp:Textbox><span style="color:red">*</span></td>
<td class="narrow"><asp:Textbox runat="server" Text='<%#Bind("StockAmount")%>' TextMode="Number" ID="Label4"></asp:Textbox></td>
<td class="narrow"><asp:Label runat="server" Text='<%#Bind("AvailableAmount")%>' ID="faxEdit"></asp:Label></td>
<td class="narrow"><asp:Checkbox runat="server" Checked='<%#Bind("ProductStatus")%>' Enabled="true" ID="Label6"></asp:Checkbox></td>
<td class="wide" style="text-align:center;"> <asp:LinkButton ID="UpdateButton" ToolTip='<%#Eval("ProductID")%>' OnClick="UpdateButton_Click" runat="server" CommandName="Update" Text="Save" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
</tr>
</EditItemTemplate>
C#:
protected void UpdateButton_Click(object sender, EventArgs e)
{
???
}
答案 0 :(得分:1)
我还没有测试,但它应该是这样的:
protected void UpdateButton_Click(object sender, EventArgs e)
{
if (e.CommandName == "Cancel")
{
ListViewDataItem lvd = (ListViewDataItem)((Control)e.CommandSource).NamingContainer;
//Same two lines for each value
Label ID = lvd.FindControl("idLabel") as Label;
string id = id.ToString();
}
}
答案 1 :(得分:1)
将按钮的CommandArgument设置为ProductId(假设这是您的主键)。
<asp:LinkButton ID="UpdateButton" ToolTip='<%#Eval("ProductID")%>' OnClick="UpdateButton_Click" runat="server" CommandArgument='<%#Eval("ProductID")%>' CommandName="Update" Text="Save" />
然后从事件中的按钮获取主键。并使用它来加载数据,进行更新,并保存到数据库。
protected void UpdateButton_Click(object sender, EventArgs e)
{
LinkButton btn=sender as LinkButton;
string productid=btn.CommandArgument;
//now update your data
}