简体   繁体   English

如何使用变量C#动态设置控件

[英]How to dynamically set a control using variables C#

How do you dynamically call a control and set it property at runtime? 如何在运行时动态调用控件并设置其属性?

// Declare and set queue servers
string[] queueservers = new string[] { "SERVER1", "SERVER2", "SERVER3", "SERVER4" };
int y;

for (y = 0; y <= queueservers.Length - 1; y++)
{
   string queueanswer = GetMailQueueSize(queueservers[y]);
   if (queueanswer == "alarm")
   {
      phxQueueImg + queueservers + .ImageUrl = "~/images/Small-Down.gif";
   }
   else
   {
      phxQueueImg + queueservers + .ImageUrl = "~/images/Small-Up.gif";
   }
   queueanswer = "";
}

See here about asking good questions . 看到这里问好问题。

I'm going to assume you pasted the wrong code since it doesn't seem to have anything to do with the question afaik. 我假设您粘贴了错误的代码,因为它似乎与afaik问题无关。 Plus could edit your question and tag if this is winform, wpf or web? 另外,如果这是Winform,WPF或Web,还可以编辑您的问题和标签?

Here I dynamically create the control at runtime: 在这里,我在运行时动态创建控件:

Textbox c = new Textbox();

Set its text, eg 设置其文字,例如

string s = "Please paste code that relates to your question";
c.Text = s;

Or here I dynamically set my textbox controls property using variables: 或者在这里,我使用变量动态设置文本框控件属性:

propertyInfo = c.GetType().GetProperty(property); 
if (propertyInfo != null)
{
    propertyInfo.SetValue(c, value, null);
}

尝试使用FindControl("controlID") ,然后将此调用的结果FindControl("controlID")转换为所需的控件类型并设置所需的属性。

(SomeParentControl.FindControl("IDOfControlToFind") AS LinkButton).PostBackUrl = "~/someresource.aspx";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM