Deleting a row in a 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
 
C

C Addison Ritchie

I'll take a stab at this since nobody else is stepping up. Granted it is not
pretty but it works.

The way you have your elements setup you essentially have a DataGrid with
one cell that has two controls in it. Well really it has 5 controls but we
are only concerned with the two... the checkbox and the hyperlink.

Your DataKeyField is accessiable through the grid's DataKeys property.
Given all this we can get to all the data in the Button Click event.

Again this is my first attempt so there may be better ways.

// go through all the items in the grid
for (int i = 0; i < grdUpload.Items.Count; i++)
{
// your checkbox is at index 1 in the controls collection
// the hyperlink is at index 4
CheckBox chkBox = (CheckBox)grdUpload.Items.Cells[0].Controls[1];
if (chkBox.Checked)
{
int key = (int)grdUpload.DataKeys;
// do whatever you need to do here
}
}

HTH,
 

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,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top