如何不被索引获取列名的单元格值的GridView在asp.net [英] How to get the cell value by column name not by index in GridView in asp.net

查看:211
本文介绍了如何不被索引获取列名的单元格值的GridView在asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GridView控件在asp.net现在我要在单元格值按列名而不是由细胞指数。

I am having a gridview in asp.net and now I want the cell value by the column name but not by the cell index.

如何将有可能由单元格列名称检索单元格的值

How would be it possible by retrieving the cell value by the cell column name

推荐答案

GridView控件不作为列名,因为这是它的数据源物业知道这些事情。

GridView does not act as column names, as that's it's datasource property to know those things.

如果您还需要知道给定列名的索引,那么你可以创建一个辅助的方法来做到这一点作为 GridView控件标题通常包含此信息。

If you still need to know the index given a column name, then you can create a helper method to do this as the gridview Header normally contains this information.

int GetColumnIndexByName(GridViewRow row, string columnName)
{
    int columnIndex = 0;
    foreach (DataControlFieldCell cell in row.Cells)
    {
        if (cell.ContainingField is BoundField)
            if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
                break;
        columnIndex++; // keep adding 1 while we don't have the correct name
    }
    return columnIndex;
}

记住,code以上会使用的BoundField ...然后用它喜欢的:

remember that the code above will use a BoundField... then use it like:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int index = GetColumnIndexByName(e.Row, "myDataField");
        string columnValue = e.Row.Cells[index].Text;
    }
}

我强烈建议你使用模板列拥有自己的控件,那么它更容易抓住像那些控件:

I would strongly suggest that you use the TemplateField to have your own controls, then it's easier to grab those controls like:

<asp:GridView ID="gv" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

,然后用

string columnValue = ((Label)e.Row.FindControl("lblName")).Text;

这篇关于如何不被索引获取列名的单元格值的GridView在asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆