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

时间:2022-06-05 00:03:09

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 = "";
}

2 个解决方案

#1


1  

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. 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);
}

#2


0  

try FindControl("controlID") and then cast the result of this call to the required control type and set the needed property.

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

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

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

#1


1  

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. 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);
}

#2


0  

try FindControl("controlID") and then cast the result of this call to the required control type and set the needed property.

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

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

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