[英]Passing DataSource ID to code-behind on checkbox check
目前,我有一個ListView,其中填充了一個綁定集合,該集合是從一個預先存在的數據庫中填充的。
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="chkDelete" runat="server" AutoPostBack="false" /></td>
<td><%#DataBinder.Eval(Container.DataItem, "team_name") %></td>
<td><%#DataBinder.Eval(Container.DataItem, "team_city") %></td>
<td><%#DataBinder.Eval(Container.DataItem, "team_stateprov") %></td>
<td><%#DataBinder.Eval(Container.DataItem, "team_country") %></td>
</tr>
</ItemTemplate>
本質上,我要執行的操作是:當我單擊“刪除”按鈕時,我想查找所有選中的chkDelete,並將相應的“ id”的Container.DataItem放入后面的代碼中,以便從那里進行刪除。 可能嗎? 如果是這樣,我應該怎么做?
您只需要遍歷ListView.Items
集合即可完成此操作。
在您的刪除按鈕單擊事件中,您只需要類似以下內容:
// Create some collection to store the IDs
List<string> itemsToDelete = new List<string>();
// Loop through all of the items, check if the box
// is checked, add to list if it is
foreach (ListViewItem item in yourListView.Items)
{
CheckBox chkDelete = (CheckBox)item.FindControl("chkDelete");
if(chkDelete.Checked)
{
string yourID = item.DataItem["id"].ToString();
itemsToDelete.Add(yourID);
}
}
注意:我認為您可以按照上述方法訪問DataItem字段。 如果這不起作用,則必須將其強制轉換為DataRowView並以這種方式進行抓取:
DataRowView data = (DataRowView)item.DataItem;
string yourID = data["id"].ToString();
自從我使用此控件已經有一段時間了,所以我並不樂觀。 但是其中之一應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.