我在ASP.NET中有一个gridview
,现在我想要单元格值by the column name,而不是按单元格索引.
如何通过单元格列名检索单元格值
我在ASP.NET中有一个gridview
,现在我想要单元格值by the column name,而不是按单元格索引.
如何通过单元格列名检索单元格值
GridView
不作为列名,因为知道这些是datasource
的属性.
如果您仍然需要知道给定列名的索引,那么可以创建一个helper方法来实现这一点,因为gridview
头通常包含此信息.
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
记住上面的代码将使用BoundField
...然后像这样使用:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
string columnValue = e.Row.Cells[index].Text;
}
}
我强烈建议您使用TemplateField
来拥有您自己的控件,这样可以更容易地抓取这些控件,例如:
<asp:GridView ID="gv" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
然后使用
string columnValue = ((Label)e.Row.FindControl("lblName")).Text;