Deleting row in Datagrid

L

Lisa

Hey all,
I've spent an hour reading posts to see how to delete a row in a
datagrid but none of them work for me (most are VB.NET and I'm coding
in C#). Specifically, I have a checkbox next to each row and a
"Delete" button at the bottom. What I want is for each row that is
checked to get deleted on the click event.... this is what I got..

<asp:datagrid id="grdUpload" runat="server" DataKeyField="UploadID"
AutoGenerateColumns="false" width="424px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox id="delete" runat="server"></asp:CheckBox>
<asp:HyperLink target=_blank id="hlUploadLink" NavigateUrl='<%#
DataBinder.Eval(Container.DataItem, "URL") %>' Runat="server"
CssClass="NormalBold">
<%# DataBinder.Eval(Container.DataItem, "File") %>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
<asp:Button id="btnDelete" runat="server" Text="Delete"></asp:Button>

What do I put in the code behind private void btnDelete_Click to
delete the record selected?

Thanks in advance!
Lisa
 
K

Karl

Lisa,
Something like this should work:
private void btnDelete_Click(object sender, System.EventArgs e) {
for (int i = 0; i < grdUpload.Items.Count; i++){
DataGridItem item = grdUpload.Items;
if(item.ItemType == ListItemType.Item || item.ItemType ==
ListItemType.AlternatingItem){
CheckBox delete = (CheckBox)item.FindControl("delete");
if(delete != null && delete.Checked == true){
int key = (int)grdUpload.DataKeys[item.ItemIndex];
//Do something with the key, like DeleteItem(key);
}
}
}
}

make sure you aren't rebinding your datasource on PostBack.

Karl
 
L

Lisa Boo

Karl,
Thanks so much for your reply but when I tried it, it does not recognize
that I've checked a record, so the delete.checked == false and it
bypasses my delete code. Any ideas?
 
K

Karl

My guess is that you are rebinding on postback. Wrap your databinding code
in a postback check:

turn -->
grdUpload.DataSource = xxx;
grdUpload.DataBind();

to-->
if (!Page.IsPostBack){
grdUpload.DataSource = xxx;
grdUpload.DataBind();
}

Karl
 
L

Lisa Boo

Karl,
Such a blonde moment - my Request.IsAuthenticated function in my
Page_load was set to true because I was testing something earlier and
forgot to change it back....so my login was failing.... and my postback
was a little different then what you provided me - so with both changes
- it works b-e-a-u-t-i-f-u-l-l-y. Thanks buddy - you ROCK!

~L~
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top