您的位置:首页 > 其它

Win窗体控件的动态添加及其控制问题

2007-03-30 10:06 351 查看
Win窗体控件的动态添加及其控制问题
使用语言:C#

一、动态添加控件代码:

Hashtable mht = new Hashtable();// 为操作动态添加的控件,特添加此代码

int N=10;

GroupBox [] testGroupBox=new GroupBox
;
for(int i=0;i<N;i++)
{
#region 动态添加GroupBox控件
testGroupBox[i]=new GroupBox();
testGroupBox[i].Location=new Point(30,60+120*i);
testGroupBox[i].Size=new System.Drawing.Size(900,100);
testGroupBox[i].Text=(i+1).ToString();
this.Controls.Add(testGroupBox[i]);
#endregion


#region 动态添加Label控件

Label [] correctLabel=new Label
;
correctLabel[i]=new Label();
correctLabel[i].Location=new Point(10,10);
correctLabel[i].Size=new System.Drawing.Size(15,15);
correctLabel[i].Text=="singleRadioButton["+i.ToString()+"][1]";
correctLabel[i].ForeColor=Color.Red;
correctLabel[i].Visible=false;
correctLabel[i].Name="Label["+i.ToString()+"]";
mht[correctLabel[i].Name]=correctLabel[i];// ◆

testGroupBox[i].Controls.Add(correctLabel[i]);
#endregion


#region 动态添加RadioButton控件
RadioButton [] singleRadioButton=new RadioButton[4];
for(int j=0;j<4;j++)
{
singleRadioButton[j]=new RadioButton();
singleRadioButton[j].Name="singleRadioButton["+i.ToString()+"]["+j.ToString()+"]";
mht[singleRadioButton[j].Name]=singleRadioButton[j];// ◆
singleRadioButton[j].Location=new Point(10+210*j,10);
singleRadioButton[j].Size=new System.Drawing.Size(200,50);


switch (j)
{
case 0:
singleRadioButton[j].Text="A:";
break;
case 1:
singleRadioButton[j].Text="B:";
break;
case 2:
singleRadioButton[j].Text="C:";
break;
case 3:
singleRadioButton[j].Text="D:";
break;
}


testGroupBox[i].Controls.Add(singleRadioButton[j]);
#endregion
}
}


二、操作动态添加的控件。

为操作动态添加的控件,特声明一中第一行的代码和注释为“◆”的所在行的代码。

操作代码如下:

strRadioButtonName=((Label)mht["Label["+i.ToString()+"]"]).Text;
if(mht.Contains(strRadioButtonName))// 判断该控件是否存在
{
if(((RadioButton)mht[strRadioButtonName]).Checked==true)
{
((Label)mht["Label["+i.ToString()+"]"]).Text="●";
}
else
{
((Label)mht["Label["+i.ToString()+"]"]).Text="Х";
}
((RadioButton)mht[strRadioButtonName.Substring(0,strRadioButtonName.Length-3)+"[0]"]).Enabled=false;
((RadioButton)mht[strRadioButtonName.Substring(0,strRadioButtonName.Length-3)+"[1]"]).Enabled=false;
((RadioButton)mht[strRadioButtonName.Substring(0,strRadioButtonName.Length-3)+"[2]"]).Enabled=false;
((RadioButton)mht[strRadioButtonName.Substring(0,strRadioButtonName.Length-3)+"[3]"]).Enabled=false;
}
else
{
((Label)mht["Label["+i.ToString()+"]"]).Text="?";
}
((Label)mht["Label["+i.ToString()+"]"]).Visible=true;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: