I'm trying to access the value of a cell in my GridView
. I want to access the value by the cell's name, rather than by the index. How can I do this?
I do not want to access the cell by its index because there is a chance that it will change positions at any time. I know that Cells[0]
would give me the value of the first index, but how about if I want to do something like Cells["NameOfCell"]?
Note: I cannot use the GridView
events because all the existing code is doing it in a function called Bind()
and they have something like this
public void Bind()
{
foreach (GridViewRow row in GridView1.Rows)
{
//nee开发者_如何学Cd to access the specific value here by name
//I know this is wrong but you get the idea
string test = row.Cells["NameOfCell"].ToString();
}
}
just 4 fun:
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;
}
}
the same, not using 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;
}
}
}
If possible, get the data from your data source - the GridView should be used for displaying data and not retrieving it. It's bound to your data source, so you should be well-equipped to read from the data source too.
You can get the value from the GridView Row DataItem
See here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx
精彩评论