配置人員在使用配置端時,會傳入一組數組,用戶端需要根據該數組自動生成相應CheckedListBox控件的Items項。這是前兩天項目的需求,做個小記錄吧!
1.生成控件:接收傳入的數組,循環周遊該數組,得到SArray,将其添加到CheckedListBox的Items。(其他控件類似)
private void ControlArrayAdd()
{
CheckedListBox ch = new CheckedListBox();
ch.Location = new Point(10, 20);
ch.Size = new Size(100, 100);
string[] array = { "選項1", "選項2", "選項3" };
foreach(string SArray in array)
{
ch.Items.Add(SArray);
this.Controls.Add(ch);
}
}
2.自适應最大Items寬度:
CheckedListBox chb = new CheckedListBox();
private void CheckedStringAdd()
{
chb.Location = new Point(20, 20);
chb.Size = new Size(70, 90);
for (int i = 0; i < 11; i++)
{
chb.Items.Add("RRRRRRRRRRRRRRRRRRRRR" + i.ToString());
this.Controls.Add(chb);
//擷取Items字元串的長度
SizeF fSize = chb.CreateGraphics().MeasureString(chb.Items[0].ToString(),chb.Font);
chb.Width = Convert.ToInt32(fSize.Width) + 40;
}
}