Wednesday, 16 November 2011

girdview values delete by combo box in asp.net

HTML clipboard
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="SqlDataSource1" AllowPaging ="true" DataKeyNames ="Roll">
            <Columns>
                <asp:TemplateField HeaderText="ROLL">
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("Roll") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:goelConnectionString %>"
            SelectCommand="SELECT * FROM [stu]"></asp:SqlDataSource>
  
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
        style="width: 74px" Text="DELETE" />
    </form>
 
 
protected void Button1_Click(object sender, EventArgs e)
{

        bool atLeastOneRowDeleted = false;
     foreach (GridViewRow row in GridView1.Rows)

    CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
    if (cb != null && cb.Checked)
{
        atLeastOneRowDeleted = true;
        // First, get the ProductID for the selected row
    int productID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value); // "Delete" the row
   

    SqlConnection sq = new SqlConnection("data source=MCQL;initial catalog=goel;user id=sa;password=lko.123");
    sq.Open();
    SqlCommand cmd = new SqlCommand("delete from stu where Roll='" + productID.ToString() + "'", sq);
    cmd.ExecuteNonQuery();
    Label1.Text += string.Format("This would have deleted ProductID {0}<br />", productID);
}
        // Show the Label if at least one row was deleted...
Label1 .Visible = atLeastOneRowDeleted;
   
    }

No comments:

Post a Comment