I have a GridView with some data from my database.
However, when hovering the delete link, it links to the incorrect ID.
I want it to use the ID from the database.
This question is very much related to this one – but it never received an answer.
My GridView code looks like this:
<asp:GridView ID="GridView1" runat="server" OnRowDeleting="GridView1_RowDeleting1" AutoGenerateColumns="false" DataKeyNames="id">
<Columns>
<asp:BoundField HeaderText="Name" DataField="name" />
<asp:BoundField HeaderText="Email" DataField="email" />
<asp:BoundField HeaderText="Comment" DataField="comment" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
How do I make the DeleteButton link to the correct ID?
Update
Page-load code that puts the data in the datatable:
protected void Page_Load(object sender, EventArgs e)
{
DataTable commentsTable = null;
commentsTable = new DataTable("Comments");
using (SqlDataReader reader = studentManager.getCommentsFromDB())
{
commentsTable.Load(reader);
GridView1.DataSource = commentsTable;
GridView1.DataBind();
}
}
getCommentsFromDB:
public SqlDataReader getCommentsFromDB()
{
SqlConnection conn = dal.connectDatabase();
conn.Open();
cmd = new SqlCommand(@"SELECT id, name, email, comment FROM GuestBook", conn);
rdr = cmd.ExecuteReader();
return rdr;
}
There’s a number of ways you can go about doing this. I tend to use an ASP.NET Button and set the
CommandNameproperty to"Delete".or
or
Then it’s just a matter of wiring up the event that handles
OnRowDeleting.… and the method to call each time that you want to refresh the
GridView. It’s much cleaner to have yourGridViewbinding call in it’s own method that you can call from anywhere in the page (which means that you can call it from your page load event as well).