2011-10-12 121 views
0

我试图访问我的GridView中单元格的值。我想通过单元格的名称而不是索引访问该值。我怎样才能做到这一点?从特定的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(); 
    } 
} 
+0

你能发布标记?如果您将值绑定到特定单元格内的控件,则很容易检索。但是,您只是评估价值并将其放置在单元格中,这大大限制了您的选择。 – jwiscarson

回答

1

仅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; 
    } 
} 

一样,不使用的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; 
     } 
    } 
} 
1

如果可能,从数据源获取数据 - GridView应该用于显示数据,而不是检索它。它绑定到你的数据源,所以你应该能够很好地从数据源读取数据。