在用户控件列表框元素工作 [英] Working with ListBox elements in a user control

查看:109
本文介绍了在用户控件列表框元素工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含(为简单起见)两个控件的用户控件(ucMarket):一个列表框(ucListBox)和标签(ucLabel)。我需要创建动态(取决于从DataSet的结果)页面上的用户控件的多个实例,我使用foreach语句添加它们,以下内容:

I have a user control (ucMarket) which contains (for the purpose of simplicity) two controls: a ListBox (ucListBox) and a Label (ucLabel). I need to create multiple instances of that user control on the page dynamically (depending on the results from a DataSet), and I add them using a foreach statement and the following:

Panel1.Controls.Add(ucMarket1);

不过,我如何才能获得像行列表框属性?到目前为止,我发现的唯一的事情就是投控制作为一个列表框:

But how do I get access to the ListBox properties like Rows ? The only thing I have found so far is to cast the control as a ListBox:

ListBox listBox1 = (ListBox)ucMarket1.FindControl("ucListBox");
listBox1.Rows = 10;

有关标签的一部分,我想我也可以做同样的事情:

For the Label part, I guess I can also do something similar:

label1 = (Label)ucMarket1.FindControl("ucLabel");

不过,我怎么把这些信息反馈到用户的控制?有没有办法直接与用户的控制,而不是铸造工作?

But then, how do I put that information back into the user control ? Is there a way to work directly with the user control instead of casting ?

推荐答案

OK了几件事情。从一个命名约定一点,不叫标签和放大器;列表框,ucSOMETHING。这是从你的例子非常混乱,不清楚你指的asp:Label控件或一些自定义的用户控件你写。至于访问您的控制。

Ok a couple of things. from a naming convention point of view, don't call the label & listbox, ucSOMETHING. This is very confusing and not clear from your example whether you're referring to the asp:Label control or some custom userControl you've written. As for accessing your controls.

我假设你正在创建并以下列方式加入一些用户控件。

I'm assuming you are creating and adding a bunch of user controls in the following manner.

for(int i = 0; i < 5; i++)
{
   var control = Page.LoadControl("~/Path/To/ucMarket.ascx");
   control.Id = "ucMarket" + i;
   Panel1.Controls.Add(control);
}

所以,最好的办法是暴露在你的控制作为一种公共财产列表框。

So your best bet is to expose the Listbox on your Control as a public property.

public class ucMarket : UserControl
{
   public ListBox TheListBox
   {
       get { return ucListBox; }
   }
}

这样,你可以访问你的列表框以下列方式。

That way you could access your listbox in the following way.

var ctrl = Panel1.FindControl("ucMarket1") as ucMarket;
ctrl.TheListBox.Rows ;

这篇关于在用户控件列表框元素工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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