简体   繁体   中英

Get column values of gridview

I am trying to get the values of cells of a gridview. I am able to access it via label name like this

Label cell1 = ((Label)e.Row.FindControl("cellLabel"));

There are 15-20 columns present, so I want to access the cells via index. I tried it with e.Row.Cells[2].Text but I am getting null here.

I cannot access the gridview directly since it is an inner gridview. How can I access the cell value in RowDatabound ?

Sample Gridview

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"

    DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">

    <Columns>

        <asp:TemplateField>

            <ItemTemplate>

                <img alt = "" style="cursor: pointer" src="images/plus.png" />

                <asp:Panel ID="pnlOrders" runat="server" Style="display: none">

                    <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">

                        <Columns>

                            <asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />

                            <asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />

                        </Columns>

                    </asp:GridView>

                </asp:Panel>

            </ItemTemplate>

        </asp:TemplateField>

        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />

        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />

    </Columns>

</asp:GridView>

gvOrders is the inner gridview.

You can get it directly from the datasource

string str = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "YourColumnName"));

To access it via index you can try

string str = ((DataBoundLiteralControl)e.Row.Cells[x].Controls[y]).Text;
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string name = e.Row.Cells[0].Text;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM