这里是一个示例代码,演示如何遍历不同类型的控件并创建用于复制的字符串构建器:
using System;
using System.Text;
using System.Windows.Forms;
public class ControlTraversal
{
// 递归遍历控件和其子控件
public static void TraverseControls(Control control, StringBuilder stringBuilder)
{
if (control != null)
{
// 判断控件类型并执行相应操作
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
stringBuilder.AppendLine("TextBox: " + textBox.Text);
}
else if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
stringBuilder.AppendLine("CheckBox: " + checkBox.Checked);
}
else if (control is RadioButton)
{
RadioButton radioButton = (RadioButton)control;
stringBuilder.AppendLine("RadioButton: " + radioButton.Checked);
}
else if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
stringBuilder.AppendLine("ComboBox: " + comboBox.SelectedItem);
}
else if (control is ListBox)
{
ListBox listBox = (ListBox)control;
foreach (var item in listBox.SelectedItems)
{
stringBuilder.AppendLine("ListBox: " + item.ToString());
}
}
// 递归遍历子控件
foreach (Control childControl in control.Controls)
{
TraverseControls(childControl, stringBuilder);
}
}
}
public static void Main()
{
// 创建一个Form并添加不同类型的控件
Form form = new Form();
TextBox textBox = new TextBox();
CheckBox checkBox = new CheckBox();
RadioButton radioButton = new RadioButton();
ComboBox comboBox = new ComboBox();
ListBox listBox = new ListBox();
form.Controls.Add(textBox);
form.Controls.Add(checkBox);
form.Controls.Add(radioButton);
form.Controls.Add(comboBox);
form.Controls.Add(listBox);
// 遍历控件并创建用于复制的字符串构建器
StringBuilder stringBuilder = new StringBuilder();
TraverseControls(form, stringBuilder);
// 打印结果
Console.WriteLine(stringBuilder.ToString());
}
}
这段代码创建了一个ControlTraversal
类,其中包含一个静态方法TraverseControls
用于递归遍历控件和其子控件,并根据不同的控件类型执行相应的操作,将结果添加到字符串构建器中。在Main
方法中,创建了一个Form
并添加了不同类型的控件,然后调用TraverseControls
方法遍历控件并创建用于复制的字符串构建器,最后打印结果。
上一篇:遍历不同的数组维度
下一篇:遍历不同索引位置的元素