日期:2014-05-19  浏览次数:20797 次

如何取得GridView内部控件的值?马上给分,在下先谢谢了!
GridView1绑定了一个数据源,在GridView1中使用了两个模板列,一列是一个Label1控件,,另一列是一个Button1,现在想在Button1_Click下取得Label1的Text?
我这样做不行string   a   =   (Label)GridView1.FindControl( "Lable1 ")).Text;
错误“未将对象引用设置到对象的实例   (Label)GridView1.FindControl( "Lable1 ")).Text
请大家指点,怎么样才能得到Label1的值

------解决方案--------------------
((Label)GridView1.Rows[((GridViewRow)((LinkButton)sender).Parent.Parent).RowIndex].FindControl( "Label1 ")).Text;

上面的写错了点,前面改成Label
------解决方案--------------------
这样办就行了
直接在GridView中找Label是找不到的,必须在Label的父控件中找,你的情况就很简单了,因为Button和Label同属于一个GridViewRow,知道Button,就可以通过btn.Parent来获得GridViewRow的引用,然后通过GridViewRow.FindControl( "Lable1 ")就可以找到Label了
------解决方案--------------------
1.添加button的属性 CommandName= "edit "
2.添加gridview的事件 OnRowEditing
3.在事件代码中
Lablel label = this.GridView.Rows[e.NewEditIndex].FindControl( "Lable1 ") as Lablel;
string s = label.Text
------解决方案--------------------
1. 给按钮个CommandName 假设为Test
2. 在GridView1_RowCreated,把当前行索引赋给按钮的CommandArgument属性

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
LinkButton addButton ;
if (e.Row.RowType == DataControlRowType.DataRow)
{
addButton = (LinkButton)e.Row.Cells[1].Controls[0];
if (addButton != null)
{
if (addButton.CommandName== "Test ")
addButton.CommandArgument = e.Row.RowIndex.ToString();
}
}
}
3. 在GridView1_RowCommand中进行处理...
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Test ")
{
Response.Write(((Label)GridView1.Rows[Convert.ToInt32(e.CommandArgument)].Cells[2].Controls[1]).Text);
}
}