dodgerfan
asked on
Delete from Gridview
What is the best way to delete a record from a gridview using code-behind? Right now I have a gridviiew that is bound in code behind with a datareader. I've seen it implemented in the ASP page, but I want to keep the code in the .aspx.cs file. Is there an example?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
use your smart tag on the design view and configure source and you can add a delete , insert, select button with that..it will automatically insert the code into the code behind...
ASKER
Some of this has been helpful, but I'm still working it. My code looks like this:
GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false " onRowCommand="GridView1_Ro wCommand">
<columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="DeleteRecord" CommandName="Delete" runat="server" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PI_Key" Visible="false" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Desc" HeaderText="Description" />
</Columns>
</asp:GridView>
Code behind DataBind:
string strQuery="select * from vw_Information";
SqlCommand cmd1 = new SqlCommand(strQuery, cn);
using(SqlDataReader dr = cmd1.ExecuteReader())
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
Code for delete so far:
{
string strDelete = "Delete from Information where PI_ley=@PI_Key";
SqlCommand cmdDelete = new SqlCommand(strDelete, cn);
cmd.Delete.Parameters.Add( @PI_key", );
cn.Open();
cmd.Delete.ExecuteNonQuery ();
}
The Parameter for the delete statement is needed, and I'm not sure how to grab it. Am I on the right path?
GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false
<columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="DeleteRecord" CommandName="Delete" runat="server" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PI_Key" Visible="false" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Desc" HeaderText="Description" />
</Columns>
</asp:GridView>
Code behind DataBind:
string strQuery="select * from vw_Information";
SqlCommand cmd1 = new SqlCommand(strQuery, cn);
using(SqlDataReader dr = cmd1.ExecuteReader())
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
Code for delete so far:
{
string strDelete = "Delete from Information where PI_ley=@PI_Key";
SqlCommand cmdDelete = new SqlCommand(strDelete, cn);
cmd.Delete.Parameters.Add(
cn.Open();
cmd.Delete.ExecuteNonQuery
}
The Parameter for the delete statement is needed, and I'm not sure how to grab it. Am I on the right path?
ASKER
Got it done.