My gridview is being generated at runtime by a dataset. My first column is a template field with checkbox, how to delete a selected row? C# please.

Recommended Answers

All 20 Replies

Do you want the row to be deleted, as soon as the checkbox is clicked, or do you have a delete button and when that button is clicked you want to delete all the rows that have their checkbox clicked?

ok you have checkbox as TemplateField and it's in the first column.

add a button outside the grid.

on button click iterate through the gridview rows and
find checkbox control and check it's checked property

and see if it is checked and if yes then delete the row
else nothing.

now question is to perform deletion you require an ID

so add one more template field as label and Bind ID field to it.
and make that template field visible = false.

at the time of deletion find that control and get the id
and perform deletion.

hope that helps

could you give a sample code?

this is my current code but it's not correct

foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex]["Register_ID"].ToString();
                da = new SqlDataAdapter("delete from EnrollTbl where Register_ID='id'",con);
                ds = new DataSet();
                ds.Clear();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }

I believe Your code is looking correct. I guess if you change your current line with below one than it should be work..

string id = GridView1.DataKeys[row.RowIndex].Value.ToString();

Let us know if it's not working..

could you give a sample code?

this is my current code but it's not correct

foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex]["Register_ID"].ToString();
                da = new SqlDataAdapter("delete from EnrollTbl where Register_ID='id'",con);
                ds = new DataSet();
                ds.Clear();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
protected void DeleteSelected_Click(object sender, EventArgs e)
    {
        //iterate through gridview1.rows property
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
                da = new SqlDataAdapter("delete from EnrollTbl where Register_ID ="+id,con);
                ds = new DataSet();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

It still doesn't work.I think there's something missing. First, where's the line that looks for register id in gridview to delete in database.

It should have to work.. one thing can you please make sure whether you have set the DataKeyNames property or not in GridView tag ? If not than you need to set it with "Register_ID " your key column.

protected void DeleteSelected_Click(object sender, EventArgs e)
    {
        //iterate through gridview1.rows property
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
                da = new SqlDataAdapter("delete from EnrollTbl where Register_ID ="+id,con);
                ds = new DataSet();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

It still doesn't work.I think there's something missing. First, where's the line that looks for register id in gridview to delete in database.

Could you please explain what does datakeynames do?

Sure... It's used to Get or set an array that contains the names of the primary key fields for the items displayed in a GridView control.

It's very helpfull at the time of Updating or Deleting data from database through the gridview control.

So just make sure you have set DataKeyNames property as well in your GridView markup.

does it make sense ?

Could you please explain what does datakeynames do?

Yes, now i understand. Here's my code.

protected void DeleteSelected_Click(object sender, EventArgs e)
    {
        //iterate through gridview1.rows property
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
                string del = "delete from  EnrollTbl where Register_ID="+id;

                da = new SqlDataAdapter(del, con);
                ds = new DataSet();
                ds.Clear();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

Here's my gridview

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" AllowPaging="True" ForeColor="#333333" GridLines="None" 
            PageSize="8" Width="100%" 
            onpageindexchanging="GridView1_PageIndexChanging" 
            DataKeyNames="Register_ID">

still it doesn't work.

I have tried to execute your code and it' working fine on myend. It's deleting the row from database but when it's going to bind the grid (GridView.DataBind()), it was giving me error. I have modified the code and am using SqlCommand instead of SqlAdapter in delete button event. See the below working modified code. It;s working perfectly.

foreach (GridViewRow row in GridView1.Rows)
{
      CheckBox checkbox = (CheckBox)row.FindControl("cbRows");

      //Check if the checkbox is checked. 
      //value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
      if (checkbox.Checked)
      {
          // Retreive the fileID
          int fileID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
          con.Open();
          cmd = new SqlCommand("delete from datatest where fileID = " + fileID, con);                    
          cmd.ExecuteNonQuery();                    
          BindData();                    
      }
}

protected void BindData()
{
    sqlAdpt = new SqlDataAdapter("select * from datatest", con);
    ds = new DataSet();
    sqlAdpt.Fill(ds);
    GridView1.DataSource = ds.Tables[0];
    GridView1.DataBind();
    con.Close();
}

Now i hope it will work for you as well :-).

Let us know it will not work.

Yes, now i understand. Here's my code.

protected void DeleteSelected_Click(object sender, EventArgs e)
    {
        //iterate through gridview1.rows property
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
                string del = "delete from  EnrollTbl where Register_ID="+id;

                da = new SqlDataAdapter(del, con);
                ds = new DataSet();
                ds.Clear();
                da.Fill(ds);

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

Here's my gridview

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" AllowPaging="True" ForeColor="#333333" GridLines="None" 
            PageSize="8" Width="100%" 
            onpageindexchanging="GridView1_PageIndexChanging" 
            DataKeyNames="Register_ID">

still it doesn't work.

You're converting it to int32 but mine is to string.

This is not the case. If your is string then use directly "GridView1.DataKeys[row.RowIndex].Value.ToString()" in Where clause of your query..

try by this and let us know...

You're converting it to int32 but mine is to string.

My code

protected void DeleteSelected_Click(object sender, EventArgs e)
    {
        //iterate through gridview1.rows property
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)row.FindControl("RegistrySelector");

            if (cb.Checked)
            {
                string id = GridView1.DataKeys[row.RowIndex].Value.ToString();
                con.Open();
                SqlCommand cmd = new SqlCommand("delete from  EnrollTbl where Register_ID=" + id, con);
                cmd.ExecuteNonQuery();
                BindData();
            }
        }
    }
    protected void BindData()
    {
        da = new SqlDataAdapter("select * from EnrollTbl", con);
        ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();
    }
}

It still doesn't work. My datakey is Register_ID that is a boundfield and in a form of hyperlink.

It seems that cb.Checked is not working..

I tried checking on it by

if(cb.Checked)
{
TextBox1.Text = "Nothing wrong";
}

but it's not working even with a checkbox checked.

Can you please show how you had define TemplateField of Checkbox within your gridview ?

It seems that cb.Checked is not working..

I tried checking on it by

if(cb.Checked)
{
TextBox1.Text = "Nothing wrong";
}

but it's not working even with a checkbox checked.

<asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="RegistrySelector" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>

I can't believe this. my code is same and it;s working perfectly. did your other columns BoundField or define in TemplateField ? Can you please put your full GridView tag ?

I mean from <asp:GridView> </asp:GridView>.. Also what version of browser you are having ?

<asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="RegistrySelector" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            CellPadding="4" AllowPaging="True" ForeColor="#333333" GridLines="None" 
            PageSize="8" Width="100%" 
            onpageindexchanging="GridView1_PageIndexChanging" 
            DataKeyNames="Register_ID">
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="RegistrySelector" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:HyperLinkField DataNavigateUrlFields="Register_ID" 
                    DataNavigateUrlFormatString="Report.aspx?id={0}" 
                    DataTextField="Register_ID" HeaderText="Regiter ID" 
                    NavigateUrl="~/Report.aspx" />
                <asp:BoundField DataField="Family_Name" HeaderText="Family Name" />
                <asp:BoundField DataField="First_Name" HeaderText="First Name" />
                <asp:BoundField DataField="Date_Registered" HeaderText="Date Registered" 
                    DataFormatString="{0:M-dd-yyyy}" />
                <asp:BoundField DataField="Prc_License" HeaderText="PRC License" />
                <asp:BoundField DataField="Ship_Exp" HeaderText="Shipboard Exp." />
            </Columns>
            <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

I'm not using SQLDatasource

Its Strange..Even i am not using SQLDatasource and it's working fine on both IE and Firefox. Have you handled any Gridview events for Checkbox column ?

Another thing is as your Register_ID is string, just modified your delete query by adding single quotes..

SqlCommand cmd = new SqlCommand("delete from  EnrollTbl where Register_ID='" + id +"'", con);

I'm not using SQLDatasource

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.