C# 如何在 GridView 中获取单元格值(不使用单元格索引)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19496204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:08:18  来源:igfitidea点击:

How to get cell value in GridView (WITHOUT using cell index)

c#asp.netgridview

提问by Adrian

how to get cell value from gridview without using cell index? Let say the first column name in my table is "RowNumber".

如何在不使用单元格索引的情况下从gridview获取单元格值?假设我的表中的第一列名称是“RowNumber”。

instead of using

而不是使用

string name = GridView1.Rows[0].Cells[0].Text;

Something like

就像是

string name = GridView1.Rows[0].Cells["RowNumber"].Text;

采纳答案by Josh Darnell

You could cast the GridViewRow's DataItem propertyinto a DataRowView, and then reference the column names:

您可以将GridViewRow 的 DataItem 属性转换为 DataRowView,然后引用列名:

DataRowView rowView = (DataRowView)GridView1.Rows[0].DataItem;
string name = rowView["RowNumber"].ToString();

You can't do this from the Cellscollection, because they are just TableCell objects, and they don't know anything about the underlying data.

您不能从Cells集合中执行此操作,因为它们只是 TableCell 对象,并且它们对底层数据一无所知。

The DataItem property represents the values in that row from the underlying datasource, so that's what you want to deal with.

DataItem 属性表示来自基础数据源的该行中的值,因此这就是您要处理的内容。

回答by Smeegs

You can use datakeys to access any data you want from the row index.

您可以使用数据键从行索引中访问您想要的任何数据。

In the markup of the gridview, add all the fields you want to be able to access to the gridview.

在 gridview 的标记中,添加您希望能够访问 gridview 的所有字段。

<asp:GridView ID="gvTransactionHistory" runat="server" 
    AutoGenerateColumns="false"  
    onselectedindexchanging="gvTransactionHistory_SelectedIndexChanging" 
    DataKeyNames="ID, AnyField">

These datakeys can be accessed in the code behind with the row index

可以在后面的代码中使用行索引访问这些数据键

    var id = gvTransactionHistory.DataKeys[rowIndex].Values["ID"];
    var AnyField = gvTransactionHistory.DataKeys[rowIndex].Values["AnyField"];

回答by kns98

here is a function I wrote. since we typically get the same list of fields over and over again, I cached the index lookups.

这是我写的一个函数。由于我们通常一遍又一遍地获得相同的字段列表,因此我缓存了索引查找。

    private static readonly HybridDictionary cache = new HybridDictionary();

    public static object[] GetColumnValues(
        this GridView g, 
        int rownumber, 
        string columnNamesCommaSeparated)
    {
        var dataView = g.DataSource as DataView;
        if (dataView != null)
        {
            DataRow dataRow = dataView[rownumber].Row;
            object[] items = dataRow.ItemArray;
            DataColumnCollection columns = dataRow.Table.Columns;

            string lookupkey = g.ID + columnNamesCommaSeparated;
            var colids = cache[lookupkey] as int[];
            int columnCount;
            if (colids == null)
            {
                string[] columnNames = columnNamesCommaSeparated.Split(',');
                columnCount = columnNames.Count();
                colids = new int[columnCount];

                for (int i = 0; i < columnCount; i++)
                {
                    colids[i] = columns.IndexOf(columnNames[i]);
                }

                cache.Add(lookupkey, colids);
            }
            columnCount = colids.Length;
            var values = new object[columnCount];

            for (int i = 0; i < columnCount; i++)
            {
                values[i] = items[colids[i]] ?? "";
            }
            return values;
        }

        return null;
    }

to use it do something like

使用它做类似的事情

            object[] values = g.GetColumnValues(e.Row.DataItemIndex, "Firstname,Lastname,CompanyName");
            if (values != null)
            {
                string header = Server.HtmlEncode(values[0] + " " + values[1] + " @ " + values[2]);
            }
            // do whatever you want with this value