Select row from a gridview and pass values to a textbox

0

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

My gridview is populated, but I need to find a solution so that when I click the row, it executes a function / method that takes the values from the row and executes another function that I already have.

I have looked for several ways, but find no way down or work.

This is the aspx of my gridview. At the moment I use a Button with CommandArguments to perform my task, but I would need to change it for when clicking on the gridview row. And column 0 is a template field that expands the grid line and shows another grid with other information, but the click on the row 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>
    
asked by anonymous 17.11.2017 / 18:23

2 answers

2

The simplest and most objective way of doing such a code without much information in the question is:

Place a CommandField ( <asp:CommandField ShowSelectButton="True" /> ) in 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 creating this, add the event SelectedIndexChanged to the properties and events box:

  

Inthiseventtheroutinehappenswhenalineisselected,andthecodebelowrepresentsanideaofhowtodoit:

protectedvoidGridView1_SelectedIndexChanged(objectsender,EventArgse){vargrid=((GridView)sender);intindex=grid.SelectedRow.RowIndex;if(index>=0){if(int.TryParse(grid.Rows[index].Cells[0].Text,outvarid)){//idtemovalorcorrespondentedaprimeiracoluna//ondeovaloréoqueidentificaalinha}}}

Screenexample:

  • Screenwithoutselection:
  

  • Screenwithselection:
  

Wellthiswouldbetheprocess,butinmycaseexampleIusedEntityFrameworktopersistandretrieveinformationandthecompletecodeofWebForm:

publicpartialclassWebForm1:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){if(!IsPostBack){Load_Grid();}}protectedvoidLoad_Grid(){using(BaseDadosEntitiesbaseDados=newBaseDadosEntities()){GridView1.DataSource=baseDados.Credit.ToList();GridView1.DataBind();}}protectedvoidGridView1_SelectedIndexChanged(objectsender,EventArgse){vargrid=((GridView)sender);intindex=grid.SelectedRow.RowIndex;if(index>=0){if(int.TryParse(grid.Rows[index].Cells[0].Text,outvarid)){using(BaseDadosEntitiesbaseDados=newBaseDadosEntities()){Creditcr=baseDados.Credit.Find(id);if(cr!=null){TxtId.Text=cr.Id.ToString();TxtName.Text=cr.Name;}}}}}}

Nowyoucanadapttoyourmodewithyourroutine,justlookatthecodeandplayback.Thisisanexampleandparticularlyafirstdrafttoreallygettheinitialidea.

18.11.2017 / 03:54
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 above code:

CurrentRow.Cells = Current line selected

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

Tip: To select the entire row and not just a cell in the dataGridView, select the grid and in the properties in SelectionMode switch to FullRowSelect

    
18.11.2017 / 03:43