Search code examples
c#asp.netgridviewclone

How to duplicate (clone) existing Row in Datagridview with Button using C# ASP.NET


I have a DataGridView with a column which with button.

Now I want that with every click on the button the selected row in the DataGridView is copied and inserted directly after the selected row.

I want to duplicate all value of all columns and insert into table of my database this new row.

How can I realize this ?

Many thanks in advance.

On my code below the error is on this line

cgv.Rows.Add(gvRow.Cells[1].Text);

<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false"
    OnSelectedIndexChanged="OnSelectedIndexChanged">
    <Columns>

<asp:TemplateField ItemStyle-HorizontalAlign="Center">
    <ItemTemplate>
    <asp:ImageButton ID="btselect" runat="server"
         CommandName="Select"
         OnClick="Copy"
         ImageUrl="/aspnet/img/clone_icon.gif"
         ToolTip="Clone row" />
    </ItemTemplate>
</asp:TemplateField>    
    <asp:BoundField DataField="CustomerId" HeaderText="ID" />    
</Columns>
</asp:GridView>

    protected void Copy(object sender, EventArgs e)
    {
        GridViewRow gvRow = this.gvProducts.SelectedRow;
        DataTable cgv = null;
        if (ViewState["Customers"] != null)
        {
            cgv = ViewState["Customers"] as DataTable;
            cgv.Rows.Add(gvRow.Cells[1].Text);
            ViewState["Customers"] = cgv;
        }

        BindData();
    }

    protected void gvProducts_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.gvProducts.SelectedRow.BackColor = System.Drawing.Color.Cyan;
    }

Solution

  • Ok, you are in a good place in that you attempting to add the data row to the data source, or the datatable that you are persiting in session.

    So, I would do it this way:

    protected void Copy(object sender, EventArgs e)
    {
        GridViewRow gvRow = this.gvProducts.SelectedRow;
        DataTable cgv = null;
        if (ViewState["Customers"] != null)
        {
            cgv = ViewState["Customers"] as DataTable;
            DataRow MyNewRow = cgv.NewRow()
            MyNewRow["FirstName"] = gvRow.Cells[2].Text;
            MyNewRow["LastName"] = gvRow.Cells[3].Text;
            MyNewRow["CustomerID"] = gvRow.Cells[0];
            cgv.Rows.Add(MyNewRow);
    
            ViewState["Customers"] = cgv;
        }
    
        BindData();
    }
    

    Do remember that any template field in the GV needs to use find control, but from what you posted, it does look like using .cells[] collection should work for you.