我目前正尝试通过复选框从列表视图中删除一行(或多行)。我的代码如下所示。我在网站的类似区域使用了相同的代码但是这个代码似乎不起作用。勾选复选框,按下删除按钮,它只是重新加载页面而不删除。
页面加载
protected void Page_Load(object sender, EventArgs e)
{
DSTableAdapters.contact_messagesTableAdapter cmta = new DSTableAdapters.contact_messagesTableAdapter();
DSTableAdapters.messagesTableAdapter mta = new DSTableAdapters.messagesTableAdapter();
DSTableAdapters.user_messagesTableAdapter umta = new DSTableAdapters.user_messagesTableAdapter();
DataTable cMessageTable = cmta.GetAll();
DataTable ownerMessagesTable = umta.GetMessages("owner");
DataTable clientMessagesTable = umta.GetMessages("user");
lvContact.DataSource = cMessageTable;
lvContact.DataBind();
lvClientMessages.DataSource = clientMessagesTable;
lvClientMessages.DataBind();
lvOwnerMessages.DataSource = ownerMessagesTable;
lvOwnerMessages.DataBind();
}
标记:
<asp:ListView ID="lvContact" runat="server" DataKeyNames="contact_id">
<LayoutTemplate>
<table id="itemPlaceHolderContainer">
<tr>
<th>Message ID</th>
<th>Email Address</th>
<th>Message</th>
<th>Date</th>
</tr>
<tr runat="server" id="itemPlaceHolder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:CheckBox ID="chkContactID" runat="server" AutoPostBack="false" />
</td>
<td>
<asp:Label ID="lblContactEmail" runat="server" Text='<%#Eval("email") %>' />
</td>
<td>
<asp:Label ID="lblContactMessage" runat="server" Text='<%#Eval("message") %>' />
</td>
<td>
<asp:Label ID="lblContactDate" runat="server" Text='<%#Eval("date") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnContactDelete" runat="server"
Text="Delete Selected Messages" onclick="btnContactDelete_Click" />
代码隐藏:
protected void btnContactDelete_Click(object sender, EventArgs e)
{
// Loop through each row to find checked boxes
for (int i = 0; i < lvContact.Items.Count; i++)
{
ListViewDataItem items = lvContact.Items[i];
int iContactID = Convert.ToInt16(lvContact.DataKeys[items.DataItemIndex]["contact_id"]);
CheckBox chkBox = (CheckBox)items.FindControl("chkContactID");
if (chkBox.Checked == true)
{
Response.Write(iContactID);
// If selected to be deleted
DSTableAdapters.contact_messagesTableAdapter cmta = new DSTableAdapters.contact_messagesTableAdapter();
cmta.DeleteMessage(iContactID);
}
}
lvContact.DataBind();
}
答案 0 :(得分:5)
您是否在页面加载中填充了ListView,您可能需要
if (!IsPostBack)
{
//Fill ListView
}
我认为当网页发回帖子时,你会丢失选中的复选框。