Pages

Men

rh

11/13/2012

How to Delete the row in Gridview using C#

Example :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Pid" AllowPaging="true" AllowSorting="True" BorderColor="Black" BorderStyle="Solid" GridLines="None" ShowFooter="True" OnRowCommand="GridView1_RowCommand"
OnRowDeleting="GridView1_RowDeleting" CaptionAlign="Top" Width="118%"
>



<Columns>
    <asp:BoundField HeaderStyle-Height="29px" HeaderText="PID" DataField="PID"
        Visible="false">
        <HeaderStyle Height="29px"></HeaderStyle>
    </asp:BoundField>


    <asp:BoundField HeaderText="Postcode" DataField="Postcode" />
 

    <asp:BoundField HeaderText="Latitude" DataField="Latitude" />
 

    <asp:BoundField HeaderText="Longitude" DataField="Longitude" />
 

    <asp:BoundField HeaderText="Easting" DataField="Easting" />
 

    <asp:TemplateField>
 

     <ItemTemplate>

            <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" CommandArgument='<%# Eval("PID") %>' Text="Delete" Font-Underline="false" ForeColor="#386991"></asp:LinkButton>
                           
        </ItemTemplate>
    </asp:TemplateField>
</Columns>


</asp:GridView>

Aspx.cs code

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

protected void BindData()
 {         
   DataSet dsImage = new DataSet();


   SqlConnection con = new SqlConnection("Data Source=Chandu/SQLExpress;Initial Catalog=Test; Persist Security Info=True;User ID=sa;Password=sa;Connect Timeout=800");
          

   con.Open();
           

   SqlCommand cmd = new SqlCommand();
            

   cmd.Connection = con;
            

   cmd.CommandType = CommandType.Text;
            

    cmd.CommandText = "Select top 1000 [PID],[Postcode],[Latitude],[Longitude],[Easting]  
     FROM [Test].[dbo].[PostalCodes]";
            

    SqlDataAdapter da = new SqlDataAdapter(cmd);
          
    da.Fill(dsImage);
           

    try
    {
           if (dsImage.Tables.Count > 0)
                {
                    if (dsImage.Tables[0].Rows.Count > 0)
                    {
                        GridView1.DataSource = dsImage.Tables[0];
                        GridView1.DataBind();
                        con.Close();
                    }
                }
            }
            catch (Exception ex)
            {

            }
    }

  
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
             Int32 intPid;
             if (e.CommandName == "Delete")
             {
                 intPid = Convert.ToInt32(e.CommandArgument.ToString());


             }
 }


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
              
 }