GridView获取值方法
1. GridView1.Rows[行号].Cells[列数].Text;
注意列数从0开始,但其属性Visible为false则无法获取
2. GridView1.DataKeys[行号].Values["FEntryID"].ToString();
GridView需要设定【DataKeyNames】,其可见设置为false,也可以获取
2014-07-30新增
GridView的DataKeyNames属性设为"ID,Name"
GridView1.DataKeyNames = new string[]{ "ID","Name" };
删除事件GridView1_RowDeleting使用:
DataKey key = GridView1.DataKeys[e.RowIndex];
int id = int.Parse(key[0].ToString());//得到id字段值
string name = key[1].ToString();//得到name字段值
取值
string aaa= GridView.DataKeys[e.Row.RowIndex].Value.ToString();
在GridView1_RowDataBound事件中取值
(DataRowView)e.Row.DataItem)["FId"].ToString()
3. 利用列名进行获取
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCellcell 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;
}
其获取方式
protected void GridView_RowDataBound(objectsender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row,"myDataField");
stringcolumnValue = e.Row.Cells[index].Text;
}
}
4. 对于列为Template的数据获取方式
<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;
后两种方式来
如有更好方法请告诉偶。谢谢