[英]Getting the value from a specific Gridview Cell
我正在嘗試訪問GridView
中的單元格值。 我想通過單元格的名稱而不是索引來訪問值。 我怎樣才能做到這一點?
我不希望通過索引訪問單元格,因為它有可能隨時更改位置。 我知道Cells[0]
會給我第一個索引的值,但是如果我想做一些像Cells["NameOfCell"]?
這樣的東西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應該用於顯示數據而不是檢索數據。 它與您的數據源綁定,因此您應該具備從數據源讀取的能力。
只有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;
}
}
}
您可以從GridView Row DataItem
獲取值
請看: http : //msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.