That’s perfectly possible, but it’s not the easiest thing to do. In fact, anything to do in Web Forms that is not directly provided by the platform has its complications. As such, this can be confusing at first. I will try to explain step by step.
First, in your GridView
you must have a TemplateField
to place the "Repeat" button on ItemTemplate
.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Repetir" CommandName="Repetir"
CommandArgument="<%#Container.DataItemIndex %>" />
</ItemTemplate
</asp:TemplateField>
Now you need to listen to your Gridview’s Rowcommand event. Just add something like OnRowCommand="MinhaGridView_RowCommand"
in Gridview and create method in Codebehind:
protected void MinhaGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Repetir") MinhaGridViewRepetirLinha(e.CommandArgument);
}
Now to the Minhagridviewrepetinha method:
protected void MinhaGridViewRepetirLinha(string sLinha)
{
var numeroDaLinha = int.Parse(sLinha);
DataSourceDaGridView.Insert(numeroDaLinha, DataSourceDaGridView[numeroDaLinha]);
MinhaGridView.DataSource = DataSourceDaGridView;
MinhaGridView.DataBind();
}
Note that for this I used a List<>
as DataSource
of GridView
. I kept her using ViewState
. I’ll show you more or less how to implement.
private List<object> _dataSourceDaGridView;
protected List<object> DataSourceDaGridView
{
get
{
return _dataSourceDaGridView ?? (_dataSourceDaGridView = ViewState["Linhas"] as List<object> ?? new List<object>());
}
set
{
_dataSourceDaGridView = ViewState["Linhas"] = value;
}
}
I didn’t test that code, I just based it on a code I’ve already used. DO NOT COPY AND PASTE, OBSERVE THE CODE AND ADAPT IT TO YOUR NEEDS, AND CORRECT POSSIBLE ERRORS ALONG THE WAY.
By the way, if any mistakes are glaring, please let me know to edit my answer.
When an answer solves your problem, it is advisable to accept it. Just click on the "check" sign below the votes of the question. It will turn green. You and the author of the answer gain reputation for this.
– Maniero