如何访问在Gridview中动态添加的控件? [英] How to access control which are dynamically added inside Gridview?

查看:69
本文介绍了如何访问在Gridview中动态添加的控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我在Gridview的Rowdatabound事件中添加了一个新控件.下面是代码:

hi all,

I have added a new control in Rowdatabound event of Gridview .Below is the code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           DataRowView drv = (DataRowView)e.Row.DataItem;
           if (drv != null)
           {
               Literal ltr = e.Row.FindControl("ltr") as Literal;
               ltr.Text = drv.Row["Id"].ToString();
               if (e.Row.RowIndex == 0)
               {
                   TextBox oTB = new TextBox();
                   oTB.ID = "TextBox1";
                   e.Row.Cells[1].Controls.Add(oTB);
                   oTB = null;
               }
               if (e.Row.RowIndex == 1)
               {
                   Panel p1 = new Panel();
                   p1.Width = Unit.Pixel(500);
                   p1.Height = Unit.Pixel(200);
                   p1.ScrollBars = ScrollBars.Vertical;
                   CheckBoxList cbl = new CheckBoxList();
                   cbl.ID = "cbl";
                   cbl.RepeatColumns = 2;
                   cbl.Items.Add(new ListItem("JAKARTA", "JKT"));
                   cbl.Items.Add(new ListItem("Maharashtra", "MH"));
                   p1.Controls.Add(cbl);
                   e.Row.Cells[1].Controls.Add(p1);
               }
           }
       }
   }



我在下面编写了用于访问控制的代码,但它始终为null,



I wrote below code to access control but it always give null,

foreach (GridViewRow row in GridView1.Rows)
       {
           TextBox txt = row.FindControl("TextBox1") as TextBox;
           CheckBoxList cbl = row.FindControl("cbl") as CheckBoxList;   
       }



如何访问控件?
请帮助

[edit]已添加代码块-OriginalGriff [/edit]



How do i access the control?
Please Help

[edit]Code blocks added - OriginalGriff[/edit]

推荐答案

您不能,除非您的控件是在页面加载事件之前添加的,并且添加了相同的控件每次都这样.否则,它们将不及时存在,在这种情况下,它们的视图状态将永远无法恢复.如果您的代码在页面加载中运行,则要访问控件,这就是为什么它们不存在而不是空的原因.页面加载在数据绑定事件之前运行,预渲染在数据绑定事件之前运行.
You can''t, unless your controls are added before the page load event, and added the same way every time. Otherwise they do not exist in time, in which case their viewstate is never restored. If your code is running in page load, to access the controls, that is why they don''t exist, instead of being empty. Page load runs before data bound events, prerender runs after.


这篇关于如何访问在Gridview中动态添加的控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆