获取GridView单元格值只知道行和列索引

我认为我的问题标题非常简单。

任何帮助表示赞赏..

使用BoundField并在readonly模式下,您可以使用GridView1.Rows[x].Cells[x].Text但在编辑模式下,您必须使用Controls集合来获取控件的引用。 此方法返回Control对象。

 Control control=GridView1.Rows[x].Cells[x].Controls[0]; // later you may cast it to appropriate control class. 

如果使用模板字段,则必须从Cells集合中发出FindControl方法,以根据其ID获取控件的引用。 您也可以使用Cells[x].Controls集合。

 Control control=GridView1.Rows[x].Cells[x].FindControl("ID_Of_Control"); // later you may cast it to appropriate control class. 

编辑:

在模板字段中可能存在一个或多个具有相同名称/ ID的控件。 在这种情况下,您不能使用FindControl方法。

例:

               

现在获取Button并从第2行和第1个单元格更改其文本:

  Button btn = GridView1.Rows[1].Cells[0].Controls[1] as Button ; if(btn!=null) btn.Text = "Hello"; 

如果它是一个BoundField,你可以做到

 gv.Rows[1].Cells[1].Text; 

如果它是TemplateField,则必须获得具有所需值的控件。

 Label L = gv.Rows[1].FindControl("yourcontrolId") as Label; L.Text;