如何在asp.net的GridView中通过列名而不是通过索引获取单元格值 [英] How to get the cell value by column name not by index in GridView in asp.net
问题描述
我在 asp.net 中有一个 gridview
,现在我想要单元格值按列名,而不是按单元格索引.
I am having a gridview
in asp.net and now I want the cell value by the column name but not by the cell index.
怎么可能通过单元格列名检索单元格值
How would be it possible by retrieving the cell value by the cell column name
推荐答案
GridView
不充当列名,因为知道这些事情是 datasource
属性.
GridView
does not act as column names, as that's it's datasource
property to know those things.
如果您仍然需要知道给定列名的索引,那么您可以创建一个辅助方法来执行此操作,因为 gridview
标题通常包含此信息.
If you still need to know the index given a column name, then you can create a helper method to do this as the gridview
Header normally contains this information.
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
... 然后像这样使用它:
remember that the code above will use a BoundField
... then use it like:
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
来拥有自己的控件,这样可以更轻松地获取这些控件,例如:
I would strongly suggest that you use the TemplateField
to have your own controls, then it's easier to grab those controls like:
<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;
这篇关于如何在asp.net的GridView中通过列名而不是通过索引获取单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!