1

I have a grid on my page and using check box for checking one or more than one row in grid and i want to delete checked row from grid on the click of delete button which is out side the grid..

In table i have only name field there is no field like ID.

How can i delete record.

Thanks in advance..

Here is my code What i am doing:-

private void GetData()
{

    ArrayList arr;
    if (ViewState["TotalRecords"] != null)
    {
        arr = (ArrayList)ViewState["TotalRecords"];
    }
    else
    {
        arr = new ArrayList();
    }
    for (int i = 0; i < grdlistWord.Rows.Count; i++)
    {

        CheckBox chk = (CheckBox)grdlistWord.Rows[i].Cells[1].FindControl("chkWord");
        if (chk.Checked)
        {
            if (!arr.Contains(grdlistWord.Rows[i].Cells[1]))
            {
                arr.Add(grdlistWord.Rows[i].Cells[1]);
            }
        }
        else
        {
            if (arr.Contains(grdlistWord.Rows[i].Cells[1]))
            {
                arr.Remove(grdlistWord.Rows[i].Cells[1]);
            }
        }

    }
    ViewState["TotalRecords"] = arr;
}

protected void lnkbtnDelete_Click(object sender, EventArgs e)
{

    try
    {
        int count = 0;

        ArrayList arr = (ArrayList)ViewState["TotalRecords"];
        count = arr.Count;
        for (int i = 0; i < grdlistWord.Rows.Count; i++)
        {
            if (arr.Contains(grdlistWord.Rows[i].Cells[1].Text))
            {
                Response.Write(grdlistWord.Rows[i].Cells[1].Text.ToString());
                DeleteRecord(grdlistWord.Rows[i].Cells[1].Text.ToString());
                arr.Remove(grdlistWord.Rows[i].Cells[1].Text);
            }
        }
        ViewState["TotalRecords"] = arr;
        GridBind();

    }
    catch (SqlException ex)
    {
        ex.ToString();
    }

}


private void DeleteRecord(string word)
{

    string query = "delete from searchword where word=@word";

    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@word", word);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

gridview html detail:

 <fieldset>
        <legend>List</legend>
        <asp:GridView ID="grdlistWord" runat="server" DataKeyNames="word" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" OnRowDataBound="grdlistWord_RowDataBound" OnRowDeleting="grdlistWord_RowDeleting">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkWord" runat="server" onclick="check_click(this);" />

                    </ItemTemplate>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkAll" runat="server" onclick="checkAll(this);" />
                        <asp:LinkButton ID="ButtonDelete" runat="server" Text="Delete" OnClick="ButtonDelete_Click"></asp:LinkButton>
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Word" HeaderText="Word" />
                <asp:HyperLinkField HeaderText="Edit" Text="edit" DataNavigateUrlFields="Word" DataNavigateUrlFormatString="SearchWord.aspx?words={0}&amp;mode=Edit" />
                <asp:CommandField ShowDeleteButton="True" HeaderText="Delete" />
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <EmptyDataTemplate>Records not exist!</EmptyDataTemplate>
        </asp:GridView>

        <asp:HiddenField ID="hfCount" runat="server" Value = "0" />

    </fieldset>
divya
  • 405
  • 2
  • 6
  • 18
  • What is the behaviour you're seeing from this code, and what are you expecting? Are you seeing any exceptions (besides that the code won't compile)? – p.campbell May 19 '11 at 05:53
  • @p.campbell: it is not getting the word to fulfill the where condition of the delete query. – divya May 19 '11 at 05:59

2 Answers2

1

For this purpose you have set a primary key id first in your table, which you are fetching as a source of the Grid.

After binding the grid you should save that id in a hidden field. see the code below:

       <asp:GridView ID="gvwID" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="TableID">
           <Columns>
                <asp:TemplateField>
                     <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("TableID") %>'/>
                 <asp:TemplateField>
           </Columns>
       </asp:GridView>

Then in the delete button click event get the selected row ids:

        protected void Btn_Click(object sender, EventArgs e)
        {
                int[] OrderIDList = new int[gvwID.Rows.Count];

                int index = 0;

                 for (int count = 0; count < gvwID.Rows.Count; count++)
                 {
                   if (gvwID.Rows[count].FindControl("chkSelect") != null)
                    {
                       if (((CheckBox)gvwID.Rows[count].FindControl("chkSelect")).Checked)
                       {
                            if (gvwID.Rows[count].FindControl("HiddenField1") != null)
                            {
                            string OrderID = ((HiddenField)gvwID.Rows[count].FindControl("HiddenField1")).Value;
                        OrderIDList[index++] = Convret.ToInt32(OrderID);
                             }
                        }
                   }
        }

Then create an appended string from OrderIDList and pass it to the stored procedure. from the stored procedure create an xml using the appended string. Loop through the xml and get each id and perform the deletion.

see the procedure below:

              @IDList varchar(MAX)

            DECLARE @xmlUserIDs xml
    SELECT @xmlUserIDs = CONVERT(xml,'<root><cat>' +  REPLACE(@IDList,',','</cat><cat>') + '</cat></root>')// creates xml from appended string

    DELETE FROM  
        [TableName]
    WHERE 
    [TableID] IN (SELECT 
                    [Value] = T.C.value('.','int') 
                  FROM 
                    @xmlUserIDs.nodes('/root/cat') T(C));

Hope this helps you..

Harun
  • 5,109
  • 4
  • 38
  • 60
  • @Divya, The OrderIDList should be converted to a string with a seperator character (here it is a comma). This worked for me..Normally a unique id (primary key) is used to perform any update/delete operations on a particular record in db.. – Harun May 19 '11 at 11:26
  • @Divya,check the stored procedure here, it loops through the @xmlUserIDs and perform deletion for each id.. – Harun May 19 '11 at 11:38
  • @Harun: My stored procedure is completed successfully. but please can u tell me that where i should have to execute this stored procedure in code? – divya May 19 '11 at 11:42
  • @Divya, You should execute the code within your delete button click event. Check my "Btn_Click" event where i just fetch the selected ids to "int[] OrderIDList". You need to convert the "OrderIDList" to a comma seperated string and then execute the procedure after that (both within the same button click event). – Harun May 19 '11 at 11:58
  • @Harun: i did this if (grdlistWord.Rows[count].FindControl("hfCount") != null) { string OrderID = ((HiddenField)grdlistWord.Rows[count].FindControl("hfCount")).Value; OrderIDList[index++] = Convert.ToInt32(OrderID); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "[DeleteData]"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Word", OrderIDList); } – divya May 19 '11 at 12:04
  • @Divya, so your procedure is not get called or what? – Harun May 19 '11 at 12:11
  • @Harun: there is no error in stored procedure showing..it is running withour any error but unable to delete any selected record. – divya May 19 '11 at 12:15
  • @Divya, did you tried executing the procedure from sql server itself by passing a comma seperated string as parameter? – Harun May 19 '11 at 12:19
  • @Harun: sorry harun but i m not too good in coding i am working as a fresher level..so please can you tell me clearly that what i have to do? – divya May 23 '11 at 05:28
1
 protected void lnkbtnDelete_Click(object sender, EventArgs e)
        {

            int counter = 0;
            List<string> words = new List<string>();
            foreach (GridViewRow rowitem in grdlistWord.Rows)
            {
                if (((CheckBox)rowitem.Cells[0].FindControl("chkWord")).Checked == true)//i consider that the check box is in the first column index ---> 0
                {
                    counter++;
                    words.Add(rowitem.Cells[1].Text); //i consider that the word is in the second column index ---> 1
                }
            }
            /////////////////////////////////////////////////////////////
            if(counter == 0) //no checks
            {

             //show some message box to clarify that no row has been selected.

            }
            /////////////////////////////////////////////////////////////
            if (counter == 1) //one check
            {

                DeleteRecord(words[0]);
                //Show some message box to clarify that the operation has been executed successfully.

            }
            /////////////////////////////////////////////////////////////
            if (counter > 1) //more than one check
            {
                for(int i=0; i<words.Count;i++)
                   {
                     DeleteRecord(words[i]);
                   }
                   //Show some message box to clarify that the operation has been executed successfully.
            }

            grdlistWord.DataBind();
        }
Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392