How to create a dynamic GridView?

2

Someone already created a GridView where rows are already filled with values and in the last column of each row there is LinkButton "Retry" and when that LinkButton is clicked, repeat the line just below the clicked row ?

I'm using C #.

    
asked by anonymous 31.01.2014 / 13:55

1 answer

1

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.

    
31.01.2014 / 14:47