我正在尝试访问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 :(得分:1)
如果可能,从数据源获取数据 - GridView应该用于显示数据而不是检索数据。它与您的数据源绑定,因此您也应该有足够的能力来读取数据源。
答案 1 :(得分:1)
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;
}
}
}
答案 2 :(得分:0)
您可以从GridView Row DataItem
见这里:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx