且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用户控件的控件值总是使用此用户控件在页面后面的代码中返回null,为什么?

更新时间:2023-12-01 19:27:28

hmm对不起,我似乎太幼稚了,但至少有人应该回答.但经过一番挖掘就可以了.如果其他类似我的菜鸟碰到这个帖子,将会解释我做错了什么以及解决问题的方法.
我正在使用在后面的代码中创建的新实例来访问usercontrol的控件,而我已经通过
在aspx标记代码中将该控件重新注册了一个实例,从而创建了一个实例
hmm sorry guys seems like, i was being too childesh, but at least someone should answer. but ok after a little bit digging got it working. and if some other noob like me comes across this post will explain what i was doing wrong and what solved the issue.
i was accessing the controls of a usercontrol using a new instance created in code behind, while i already had created an instance by registring this control in aspx markup code by
<%@ Register src="UserControl.ascx" tagname="ucLogin" tagprefix="MyControls" %>


因此,当我使用此控件时,我给了它一个ID,如下所示


so when i used this control i gave an id to it as below

<MyControls:ucLogin ID="UserLogin"  runat="server" />

因此,通过查看此内容,我认为我也应该使用标记前缀和标记名以相同的方式在代码后面访问它,而这就是我出错的地方,可以将我的usercontrol的多个实例放置在同一页面上,与我在<%@ Register>中注册时定义的标签相同的标签.标签,即

so by looking at this, i thought i should access it the same way in code behind too by using tag prefix and tagname, and this is where i went wrong, i could place multiple instances of my usercontrol on the same page, with same tag i defined while registering it in the <%@ Register> tag, i-e

<mycontrols:uclogin ...="" xmlns:mycontrols="#unknown" />

,但请记住,在标记中创建的该控件的每个新实例都将具有不同的ID,即i-e

but remember each new instance of this control created in markup will have a different id,i-e

<MyControls:ucLogin ID="UserLogin1"  runat="server" />
<MyControls:ucLogin ID="UserLogin2"  runat="server" />
<MyControls:ucLogin ID="UserLogin3"  runat="server" />


就是这样,此id将是我们对UserControl的每个实例的引用,并且将在使用此id的后面的代码中访问该用户控件的控件. i-e
字符串UserName = UserLogin1.txtUserName.Value;

希望对您有所帮助.


and this is it, this id will be our referance to each of the instance of UserControl and will access controls of that user control in code behind using this id. i-e
string UserName = UserLogin1.txtUserName.Value;

I hope it helps someone.