bal*_*dre 67
GridView
不作为列名称,因为datasource
知道那些东西的属性.
如果您仍然需要知道给定列名的索引,那么您可以创建一个帮助方法来执行此操作,因为gridview
Header通常包含此信息.
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;
}
Run Code Online (Sandbox Code Playgroud)
请记住,上面的代码将使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
我强烈建议您使用它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>
Run Code Online (Sandbox Code Playgroud)
然后使用
string columnValue = ((Label)e.Row.FindControl("lblName")).Text;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
111896 次 |
最近记录: |