Select line from a gridview and pass the values to a textbox

Asked

Viewed 1,379 times

0

I am facing problems trying to find a solution so that when I click a grid view, it passes the values contained in the line to text boxes.

My gridview is being populated, but I need to find a solution so that when I click on the line, it performs a function/method that takes the values of the line and performs another function that I already have ready.

I’ve looked at several ways, but I can’t find any decent or working way.

This is my gridview’s aspx. At the moment I use a Button with Commandarguments to perform my task, but I would need to change this to when clicking on the gridview line. And column 0 is a template field that expands the grid line and shows another grid with other information, but the click on the line will only be on the first grid.

    <asp:Panel runat="server" ID="panelBatches" ScrollBars="Auto" Style="width: 60%; height: auto; padding: 10px; border: thin solid #000099; background-color: whitesmoke; position: relative; left: 20%; border-radius: 5px;">
        <div class="rounded_corners" style="width: 100%;">
            <asp:GridView ID="gvWeighingLogBatches" runat="Server" DataKeyNames="ID, Status" GridLines="None" HeaderStyle-CssClass="gvHeader"
                CssClass="gvRow" AutoGenerateColumns="false" OnRowDataBound="gvWeighingLogBatches_RowDataBound"
                OnPageIndexChanging="gvWeighingLogBatches_PageIdexChanging" OnRowCommand="gvWeighingLogBatches_RomwCommand"
                AllowPaging="True" PageSize="12" HorizontalAlign="Center" RowStyle-HorizontalAlign="Right" Style="width: 100%">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <img alt="" style="cursor: pointer" src="../Imagens/icon_plus.png" />
                            <asp:Panel ID="panelWeighingMaterialLogBatches" runat="server" Style="display: none;">

                                <div class="rounded_corners" style="width: 100%;">
                                    <asp:GridView ID="gvWeighingMaterialLogBatches" runat="server" Width="100%" GridLines="None" AutoGenerateColumns="false" DataKeyNames="ID"
                                        HeaderStyle-CssClass="gvChildHeader" CssClass="gvRow" AlternatingRowStyle-CssClass="gvAltRow"
                                        OnRowDataBound="gvWeighingMaterialLogBatches_RowDataBound" RowStyle-HorizontalAlign="Right">
                                        <Columns>

                                            <asp:TemplateField>
                                                <ItemTemplate>
                                                    <img alt="" style="cursor: pointer" src="../Imagens/icon_plus.png" />
                                                    <asp:Panel ID="panelWeighingLotMaterialLogBatches" runat="server" Style="display: none;">

                                                        <div class="rounded_corners" style="width: 100%;">
                                                            <asp:GridView ID="gvWeighingLotMaterialLogBatches" runat="server" Width="100%" GridLines="None" AutoGenerateColumns="false" DataKeyNames="ID"
                                                                HeaderStyle-CssClass="gvChildHeader" CssClass="gvRow" AlternatingRowStyle-CssClass="gvAltRow" RowStyle-HorizontalAlign="Right">
                                                                <Columns>
                                                                    <asp:BoundField DataField="LotManufactID" HeaderText="Lot Fabricante ID" />
                                                                    <asp:BoundField DataField="ActualAmount" HeaderText="Cantidad Real" DataFormatString="{0:F3}" />
                                                                    <asp:BoundField DataField="ExpireDate" HeaderText="Fecha de Expiración" DataFormatString="{0:dd/MM/yyyy}" />
                                                                    <asp:BoundField DataField="WeighingDateTime" HeaderText="Hora de la Fecha de Pesaje" />
                                                                </Columns>
                                                            </asp:GridView>
                                                        </div>

                                                    </asp:Panel>
                                                </ItemTemplate>
                                            </asp:TemplateField>

                                            <asp:BoundField DataField="ID" HeaderText="Id de Registro del Material de Pesaje" />
                                            <asp:BoundField DataField="Name" HeaderText="Nombre del Ingrediente" />
                                            <asp:BoundField DataField="MinAmount" HeaderText="Mínimo" DataFormatString="{0:F3}" />
                                            <asp:BoundField DataField="TargetAmount" HeaderText="Necesario" DataFormatString="{0:F3}" />
                                            <asp:BoundField DataField="MaxAmount" HeaderText="Máximo" DataFormatString="{0:F3}" />
                                            <asp:BoundField DataField="ActualAmount" HeaderText="Real" DataFormatString="{0:F3}" />
                                            <asp:BoundField DataField="WeighingDateTime" HeaderText="Hora de la Fecha de Pesaje" />
                                            <asp:BoundField DataField="Status" HeaderText="Estado" />

                                        </Columns>
                                    </asp:GridView>
                                </div>

                            </asp:Panel>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Button runat="server" ID="linkBtnViewBatches" CommandArgument='<%#Eval("BatchID") %>' CommandName="View" Text="Ver Lote"></asp:Button>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:BoundField DataField="ID" HeaderText="ID de Registro de Pesaje" Visible="False" />
                    <asp:BoundField DataField="BatchID" HeaderText="ID de Lote" />
                    <asp:BoundField DataField="Name" HeaderText="Nombre del Producto" />
                    <asp:BoundField DataField="ActualBatchSize" HeaderText="Tamaño Real del Lote" DataFormatString="{0:F3}" />
                    <asp:BoundField DataField="BatchPriority" HeaderText="Prioridad de Lote" />
                    <asp:BoundField DataField="RequestedStartTime" HeaderText="Hora de inicio Solicitada" />
                    <asp:BoundField DataField="Status" HeaderText="Estado" />

                </Columns>
            </asp:GridView>
        </div>
    </asp:Panel>
  • Share the code of what you’ve managed to do.

  • is Aspnetforms?. if you can make the code available!

2 answers

2


The simplest and most objective way to make such code without much information in the question is:

Put a CommandField (<asp:CommandField ShowSelectButton="True" />) in the GridView, complete example:

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False" 
    CellPadding="4" 
    ForeColor="#333333" 
    GridLines="None" 
    Width="691px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Nome" />
        <asp:CommandField ShowSelectButton="True"  /> // comando de seleção ...
    </Columns>
    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView> 

after you’ve created it add the event SelectedIndexChanged by the property and events box:

inserir a descrição da imagem aqui

and in this event the routine happens when some line is selected, and the code below represents an idea of how to do:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    var grid = ((GridView)sender);
    int index = grid.SelectedRow.RowIndex;
    if (index >= 0)
    {
        if (int.TryParse(grid.Rows[index].Cells[0].Text, out var id))
        {
            //id tem o valor correspondente da primeira coluna
            //onde o valor é o que identifica a linha
        }
    }
}

Screen example:

  • Screen without selection:

inserir a descrição da imagem aqui

  • Screen with selection:

inserir a descrição da imagem aqui

Well that would be the process, but in my case example I used the Entity Framework to persist and retrieve information and the complete code of WebForm:

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Load_Grid();
        }
    }

    protected void Load_Grid()
    {
        using (BaseDadosEntities baseDados = new BaseDadosEntities())
        {
            GridView1.DataSource = baseDados.Credit.ToList();
            GridView1.DataBind();
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var grid = ((GridView)sender);
        int index = grid.SelectedRow.RowIndex;
        if (index >= 0)
        {
            if (int.TryParse(grid.Rows[index].Cells[0].Text, out var id))
            {
                using (BaseDadosEntities baseDados = new BaseDadosEntities())
                {
                    Credit cr = baseDados.Credit.Find(id);
                    if (cr != null)
                    {
                        TxtId.Text = cr.Id.ToString();
                        TxtName.Text = cr.Name;
                    }
                }
            }
        }
    }
}

Now you can adapt to your mode with your routine, just look at the code and play. This is an example and particularly a first draft to really pass the initial idea.

References

  • Virgilio, your explanation was very constructive for me, but I tried to adapt to my code and gave syntax error in this part:

  • protected void gvAdjstBatchesCancel_SelectedIndexChanged(object sender, EventArgs e)&#xA; {&#xA; var grid = ((GridView)sender);&#xA; int index = grid.SelectedRow.RowIndex;&#xA;&#xA; if (index > 0)&#xA; {&#xA; if (int.TryParse(grid.Rows[index].Cells[1].Text, out var id))&#xA; {&#xA; &#xA; }&#xA; }&#xA; } In this part I put [1] because column 0 is a field template that opens another grid within itself dynamically.

  • @Matheusalvesdeoliveira in your question ask your question aspx of his GridView so I can let you know what’s going on.

  • I have provided the aspx of my grid so that you can help me if possible.

  • @Matheusalvesdeoliveira did not miss the event? ie, SelectedIndexChanged in the GridView note that in Gridview you have the method reference if it does not work!

  • this is the code without the changes, I did as you showed me and gave error in the part I showed you here in the comments.

  • Not Same As @Matheusalvesdeoliveira takes a look at the event in your gridview not registered... and the error I’m not seeing is showed no error?

  • Error appears on line if (int.TryParse(grid.Rows[index].Cells[1].Text, out var ID)) Invalid Expression term ')'

  • @Matheusalvesdeoliveira ai error is another friend is parentheses understood, is something local has how to put your code in the context of the question?

Show 5 more comments

0

Greetings.

Let’s assume a grid : myDataGridView

3 columns:

Name | Age | Sex

Carlos | - 12 - | - M

Maria | - 18 - | - F

John | - 16 - | - M

// passando valor da linha selecionada para textBox
textBoxNome.Text = Convert.ToString(meuDataGridView.CurrentRow.Cells[0].Value);
textBoxIdade.Text = Convert.ToString(meuDataGridView.CurrentRow.Cells[1].Value);
textBoxSexo.Text = Convert.ToString(meuDataGridView.CurrentRow.Cells[2].Value);

In the code above:

CurrentRow.Cells = Current line selected

Cells[x] = cell number/column for selected row

Tip: To select the entire line and not just a cell from dataGridView, select the grid and in the properties on Selectionmode change to Fullrowselect

Browser other questions tagged

You are not signed in. Login or sign up in order to post.