【问题标题】:Get column values of gridview获取gridview的列值
【发布时间】:2016-01-07 07:56:25
【问题描述】:

我正在尝试获取 gridview 的单元格的值。我可以通过这样的标签名称访问它

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

目前有 15-20 列,所以我想通过索引访问单元格。我用e.Row.Cells[2].Text 尝试过,但在这里我得到了空值。

我不能直接访问gridview,因为它是一个内部gridview。如何访问 RowDatabound 中的单元格值?

示例网格视图

<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 是内部网格视图。

【问题讨论】:

  • 显示你的 .aspx gridView
  • 最好使用 TemplateField 而不是 BoundField
  • 你是要获取父gridview还是嵌套gridview的值?

标签: c# asp.net gridview


【解决方案1】:

可以直接从数据源获取

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

要通过索引访问它,您可以尝试

string str = ((DataBoundLiteralControl)e.Row.Cells[x].Controls[y]).Text;

【讨论】:

  • 正如我所说,我不想使用名称,因为有很多,所以我想使用索引。有可能吗?
  • @HarshitShrivastava - 但是你为什么要避免名字呢?你不觉得使用index 会让你的代码容易出错吗?
  • 不,正如我所说,有很多列。所以我可以将 for 循环用于索引,因为我想在更多应用程序中使用它。使用名称将很容易在进一步的程序中而不是列中实现。
  • @HarshitShrivastava:- 更新了我的代码,但是使用名称而不是索引将是更好和推荐的方法。
【解决方案2】:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string name = e.Row.Cells[0].Text;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多