If Control is Radiobutton or Textbox
我有一个根据用户选择更改标题的表单。然后我想为控件创建一个属性,无论是单选按钮还是复选框。它们有相同的属性,但我无法很好地实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private void DeleteEdit() { Control[] EmployeesControl; //I think this is the problem, but i cant figure it out. if (Form_AddEmployee.Text.Contains("Edit")) { EmployeesControl = new RadioButton[numberOfEmployees]; } else if (Form_AddEmployee.Text.Contains("Delete")) { EmployeesControl = new CheckBox[numberOfEmployees]; } for (int i = 0; i < EmployeesControl.Count(); i++) { EmployeesControl[i] = new EmployeesControl(); InitializeControls(EmployeesControl[i]); EmployeesControl[i].Visible = true; panelEmployee.Controls.Add(EmployeesControl[i]); EmployeesControl[i].Text = stringTemp; EmployeesControl[i].Location = new Point(100, 100 * (i+1)); EmployeesControl[i].Font = MyFont; EmployeesControl[i].CheckedChanged += EmployeesDeleteEditEmployees_CheckedChanged; } } |
如果某个控件是单选按钮或复选框,如何生成变量。
在将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | private void DeleteEdit() { Control[] EmployeesControl; //I think this is the problem, but i cant figure it out. if (Form_AddEmployee.Text.Contains("Edit")) { EmployeesControl = new RadioButton[numberOfEmployees]; for (int i = 0; i < EmployeesControl.Count(); i++) { EmployeesControl[i] = new RadioButton(); } } else if (Form_AddEmployee.Text.Contains("Delete")) { EmployeesControl = new CheckBox[numberOfEmployees]; for (int i = 0; i < EmployeesControl.Count(); i++) { EmployeesControl[i] = new CheckBox(); } } ButtonBase b; CheckBox chk; RadioButton rdo; for (int i = 0; i < EmployeesControl.Count(); i++) { b = (ButtonBase)EmployeesControl[i];//You use b to set property if (EmployeesControl[i].GetType() == typeof(RadioButton)) { rdo = (RadioButton)EmployeesControl[i]; //Your code //................ rdo.CheckedChanged += EmployeesDeleteEditEmployees_CheckedChanged; } else { chk = (RadioButton)EmployeesControl[i]; //Your code //............... chk.CheckedChanged += EmployeesDeleteEditEmployees_CheckedChanged; } //EmployeesControl[i] = new EmployeesControl(); //InitializeControls(EmployeesControl[i]); //EmployeesControl[i].Visible = true; //panelEmployee.Controls.Add(EmployeesControl[i]); //EmployeesControl[i].Text = stringTemp; //EmployeesControl[i].Location = new Point(100, 100 * (i + 1)); //EmployeesControl[i].Font = MyFont; //EmployeesControl[i].CheckedChanged += EmployeesDeleteEditEmployees_CheckedChanged; } } |
我希望它能帮助你。
你可以使用ButtonBase类来处理你的问题。
通过ButtonBase声明控件数组,这样您就可以使用复选框和RadioButton的公共属性而无需强制转换。
复选框或单选按钮的属性
1 2 3 4 5 6 7 8 9 10 11 | var a = EmployeesControl[i] as CheckBox; if (a != null) { //this is checkbox continue; } var b = EmployeesControl[i] as RadioButton; if (b != null) { //this is RadioButton } |