我有一个表单,其中有许多文本框(在tabControl布局中).我正在禁用所有文本框上的右键单击功能.通过提供以下代码:
txtAmountChildPlans.ContextMenu = new ContextMenu();
txtCityHome.ContextMenu = new ContextMenu();
txtCityPersonal.ContextMenu = new ContextMenu();
txtCityRetirement.ContextMenu = new ContextMenu();
txtEmailCar.ContextMenu = new ContextMenu();
txtEmailCarIns.ContextMenu = new ContextMenu();
txtEmailHome.ContextMenu = new ContextMenu();
txtEmailOp.ContextMenu = new ContextMenu();
txtEmailPersonal.ContextMenu = new ContextMenu();
txtEmailSenior.ContextMenu = new ContextMenu();
txtEmailTwoIns.ContextMenu = new ContextMenu();
txtFullNamePersonal.ContextMenu = new ContextMenu();
txtManufacturerCar.ContextMenu = new ContextMenu();
txtMobileCar.ContextMenu = new ContextMenu();
txtMobileCarIns.ContextMenu = new ContextMenu();
txtMobileHome.ContextMenu = new ContextMenu();
txtMobileNoRetirement.ContextMenu = new ContextMenu();
txtMobileOp.ContextMenu = new ContextMenu();
txtMobilePersonal.ContextMenu = new ContextMenu();
txtMobileSenior.ContextMenu = new ContextMenu();
txtMobileTwoIns.ContextMenu = new ContextMenu();
txtModelCar.ContextMenu = new ContextMenu();
txtMonthlySalaryCar.ContextMenu = new ContextMenu();
txtNameHome.ContextMenu = new ContextMenu();
txtNameRetirement.ContextMenu = new ContextMenu();
txtPensionRetirement.ContextMenu = new ContextMenu();
txtRegCarIns.ContextMenu = new ContextMenu();
txtRegTwoIns.ContextMenu = new ContextMenu();
Run Code Online (Sandbox Code Playgroud)
编辑:
foreach (var textbox in this.Controls.OfType<TextBox>())
{
textbox.ContextMenu = new ContextMenu();
}
foreach (var textbox in this.tabCarInsurance.Controls.OfType<TextBox>())
{
textbox.ContextMenu = new ContextMenu();
}
foreach (var textbox in this.tabHealth.Controls.OfType<TextBox>())
{
textbox.ContextMenu = new ContextMenu();
}
foreach (var textbox in this.tabHomeLoans.Controls.OfType<TextBox>())
{
textbox.ContextMenu = new ContextMenu();
}
foreach (var textbox in this.tabRetirement.Controls.OfType<TextBox>())
{
textbox.ContextMenu = new ContextMenu();
}
Run Code Online (Sandbox Code Playgroud)
无论如何在sigle函数中写这个.或更少的代码?
这对我来说并不好看.css中的c#是否有任何方法可以为所有文本框提供相同的属性?
您可以枚举所有文本框并在循环中创建新的上下文菜单
foreach (TextBox textbox in AllTextBoxes(this))
{
textbox.ContextMenu = new ContextMenu();
}
public IEnumerable<TextBox> AllTextBoxes(Control control)
{
List<TextBox> result = new List<TextBox>();
result.AddRange(control.Controls.OfType<TextBox>());
foreach (var childControl in control.Controls.OfType<Control>())
{
result.AddRange(AllTextBoxes(childControl));
}
return result;
}
Run Code Online (Sandbox Code Playgroud)