GridView获取单个单元格的值

0、GridView中的所有数据都存储在Rows集合中,可以通过Rows的Cell属性获取单个单元格的值;如果某个单元格包含其他控件,则通过使用单元格的 Controls 集合,从单元格检索控件;如果控件指定了 ID,可以使用单元格的 FindControl 方法来查找该控件。

1、从 BoundField 字段列或自动生成的字段列检索字段值,请使用单元格的 Text 属性;

C#代码:

string value= GridView1.Rows[rowIdx].Cells[colIdx].Text;  

2、若要从将字段值绑定到控件的其他字段列类型检索字段值,请先从相应的单元格检索控件,然后访问该控件的相应属性。

C#代码:

 1     <asp:Label runat="server" Text='<%# Bind("Quantity") %>' id="Label1">  
 2     </asp:Label>  
 3       
 4     ...   
 5       
 6     Label Label1= (Label)GridView1.Rows[rowIdx].Cells[colIdx].FindControl("Label1");  
 7       
 8     if (Label1!= null){  
 9       // 读取 Label1.Text   
10     }  

3、对于TemplateField 字段列,可以直接使用数据绑定表达式,无需将值绑定到控件的某个属性。 在这种情况下,字段值将自动放置在 DataBoundLiteralControl 控件中。 若要检索字段值,必须先从相应单元格检索 DataBoundLiteralControl 控件,然后再使用其 Text 属性。

C#代码:

string value = ((DataBoundLiteralControl)GridView1.Rows[rowIdx].Cells[colIdx].Controls[0]).Text;  
原文地址:https://www.cnblogs.com/xiesong/p/5505636.html