【发布时间】:2021-07-13 14:13:47
【问题描述】:
我有一个使用 TableLayoutPanel 控件的 winform 项目。每个 TableLayoutPanel 单元格都有面板。这些面板有 1 个。文本框
我使用下面的代码来访问文本框。
例如;
1-) 要更改文本框的颜色,我创建了 makeColorofTexboxesYellow() 方法。
2-) 为了使文本框为空,我创建了 makeTexboxesEmpty() 方法。
如您所见;在到达文本框之前,方法中有相同的代码。
private void makeColorofTexboxesYellow()
{
for (int i = start; i < end; i++)
{
//tlp1 is name of tablelayoutpanel
Panel pnl = (Panel)tlp1.GetControlFromPosition(i, textboxOwnerIndex + 1);
foreach (Control t in pnl.Controls)
{
if (t is TextBox)
{
if ((t as TextBox).Tag == null)
{
// until here, all codes with same as following method (makeTexboxesEmpty())
((t as TextBox).BackColor=Color.Yellow;
}
}
}
}
}
private void makeTexboxesEmpty()
{
for (int i = start; i < end; i++)
{
// tlp is name of tablelayoutpanel
Panel pnl = (Panel)tlp1.GetControlFromPosition(i, textboxOwnerIndex + 1);
foreach (Control t in pnl.Controls)
{
if (t is TextBox)
{
if ((t as TextBox).Tag == null)
{
((t as TextBox).Text="";
}
}
}
}
}
如何避免重写这些代码。解决方案应该是这样的。
(我保持代码简短,以举例说明 for-ex ((t as TextBox).Text="";)
private void commonMethot()
{
for (int i = start; i < end; i++)
{
//tlp1 is name of tablelayoutpanel
Panel pnl = (Panel)tlp1.GetControlFromPosition(i, textboxOwnerIndex + 1);
foreach (Control t in pnl.Controls)
{
if (t is TextBox)
{
if ((t as TextBox).Tag == null)
{
// call methot here
makeTexboxesBackColorYellow(t as TextBox) ;
//or
makeTexboxesEmty(t as TextBox);
}
}
}
}
}
private void makeTexboxesBackColorYellow(Textbox t)
{
t.BackColor=Color.Yellow;
}
private void makeTexboxesEmty(Textbox t)
{
t.Text="";
}
但我无法解决这个问题。请帮忙。
编辑:
对不起,这是我的错。我必须更具体。
t.BackColor=Color.Yellow;
只是一个例子。这个领域有很多动作。 我添加了图片以进行更多解释。请看。
【问题讨论】:
-
你的最后一个标签似乎完全关闭了。 - 还请修复格式以使代码可读而无需 sceolling
-
commonMethod(Action<TextBox> action)...action(t as Textbox).... `commonMethod(t=>t.BackColor=Color.Yellow);或commonMethod(t=>t.Text=string.Empty);... 或类似版本的代理 -
与代表:
delegate void DoSomthingWithTextBox(TextBox t);...commonMethod(DoSomthingWithTextBox action)...action(t as Textbox)然后commonMethod(t=>t.BackColor=Color.Yellow);甚至commonMethod(makeTexboxesBackColorYellow); -
为什么不直接继承
Textbox,把你的条件放进去,然后在你需要的地方使用它呢?恕我直言,这是一个简单任务不需要的所有膨胀。触发这些例程以更改文本框背景颜色的条件是什么? -
在commin方法中添加参数:commonMethot(Color color)