C# 从特定Gridview单元格获取值

C# 从特定Gridview单元格获取值,c#,asp.net,C#,Asp.net,我正在尝试访问我的GridView中的单元格值。我希望通过单元格的名称而不是索引来访问值。我该怎么做 我不想通过索引访问单元格,因为它有可能随时改变位置。我知道Cells[0]会给我第一个索引的值,但是如果我想做Cells[“NameOfCell]”之类的事情,怎么样? 注意:我不能使用GridView事件,因为所有现有的代码都是在一个名为Bind()的函数中执行的,它们有类似的内容 public void Bind() { foreach (GridViewRow row in Gri

我正在尝试访问我的
GridView
中的单元格值。我希望通过单元格的名称而不是索引来访问值。我该怎么做

我不想通过索引访问单元格,因为它有可能随时改变位置。我知道
Cells[0]
会给我第一个索引的值,但是如果我想做
Cells[“NameOfCell]”之类的事情,怎么样?

注意:我不能使用
GridView
事件,因为所有现有的代码都是在一个名为
Bind()
的函数中执行的,它们有类似的内容

public void Bind()
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        //need to access the specific value here by name
        //I know this is wrong but you get the idea
        string test = row.Cells["NameOfCell"].ToString();
    }
}

如果可能,从数据源获取数据-GridView应该用于显示数据而不是检索数据。它绑定到您的数据源,因此您也应该具备从数据源读取数据的能力。

您可以从
GridView行数据项中获取值

请参见此处:

仅4个乐趣:

private int nameCellIndex = -1;
private const string CellName = "Name";

void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int cellIndex = 0; cellIndex < e.Row.Cells.Count; cellIndex++)
        {
            if (e.Row.Cells[cellIndex].Text == CellName)
            {
                nameCellIndex = cellIndex;
                break;
            }
        }
    }
    else if (nameCellIndex != -1 && e.Row.RowType == DataControlRowType.DataRow)
    {
        string test = e.Row.Cells[nameCellIndex].Text;
    }
}
private int-nameCellIndex=-1;
私有常量字符串CellName=“Name”;
void GridView1_RowDataBound(对象发送方,GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.Header)
{
对于(int-cellIndex=0;cellIndex
同样,不使用RowDataBound:

private int nameCellIndex = -1;
private const string CellName = "Name";

void Button1_Click(object sender, EventArgs e)
{
    for (int cellIndex = 0; cellIndex < GridView1.HeaderRow.Cells.Count; cellIndex++)
    {
        if (GridView1.HeaderRow.Cells[cellIndex].Text == CellName)
        {
            nameCellIndex = cellIndex;
            break;
        }
    }

    if (nameCellIndex != -1)
    {
        foreach (var row in GridView1.Rows.OfType<GridViewRow>().Where(row => row.RowType == DataControlRowType.DataRow))
        {
            string test = row.Cells[nameCellIndex].Text;
        }
    }
}
private int-nameCellIndex=-1;
私有常量字符串CellName=“Name”;
无效按钮1\u单击(对象发送者,事件参数e)
{
对于(int-cellIndex=0;cellIndexrow.RowType==DataControlRowType.DataRow))
{
字符串测试=行。单元格[nameCellIndex]。文本;
}
}
}

您可以发布标记吗?如果要将值绑定到特定单元格中的控件,则很容易检索。然而,您只是评估值并将其放入单元格中,这大大限制了您的选择。