Checkbox == true not detected
I am currently attempting to delete a row (or rows) from a listview via a checkbox. The code I have is below.. I have used the same on a similar area of the site however this one doesn't seem to work. The check box is ticked, the delete button is pressed and it just reloads the page without deleting.
Page Load
protected void Page_Load(object sender, EventArgs e)
{
DSTableAdapters.contact_messagesTableAdapter cmta = new DSTableAdapters.contact_messagesTableAdapter开发者_JAVA技巧();
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();
}
Markup:
<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" />
Code-behind:
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();
}
Do you populate the ListView in your page load, you might need to have
if (!IsPostBack)
{
//Fill ListView
}
I think when the webpage does a post back you loosing the checked checkboxes.
精彩评论