This is perfectly possible, but it is not the easiest thing to do. In fact, anything to do with Web Forms that is not directly provided by the platform has its complications. As such, this can be confusing at first. I'll try to explain step by step.
First of all, in your GridView
you must have TemplateField
to put the "Repeat" button in ItemTemplate
.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Repetir" CommandName="Repetir"
CommandArgument="<%#Container.DataItemIndex %>" />
</ItemTemplate
</asp:TemplateField>
Now you need to listen to the RowCommand event of your GridView. Just add something like OnRowCommand="MinhaGridView_RowCommand"
in the GridView and create the method in CodeBehind:
protected void MinhaGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Repetir") MinhaGridViewRepetirLinha(e.CommandArgument);
}
Now to the MyGridViewRepeatLine 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've used List<>
as DataSource
of GridView
. I kept it 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 DID NOT TEST THIS CODE, I JUST BASED IT ON A CODE I ALREADY USED. DO NOT COPY AND COLLECT, OBSERVE THE CODE AND ADAPT TO YOUR NEEDS, AND CORRECT THE POSSIBLE BUGS ON THE WAY.
Incidentally, if any errors are glaring, please let me know so that I can edit my answer.