更改所选动态添加文本框的颜色

时间:2018-02-08 02:52:29

标签: c# winforms

当我在文本框中单击鼠标按钮时,我正在尝试设置单个文本框的背景颜色。我有一个盒子阵列,总共81个,我动态添加到表单中。我使用var num命名为1-81。 我已经能够让它工作,但它为所有的盒子添加了颜色,而不仅仅是我选择的那个。

//array of boxes
TextBox[,] cell = new TextBox[9, 9];

//add boxes to form
for (int row = 0; row < 9; row++)
{
  for (int col = 0; col < 9; col++)
  {
   num += 1;
   cell[row, col] = new TextBox();
   cell[row, col].Name = Convert.ToString(num);
  }
}

//handler
cell[row, col].MouseDown += new MouseEventHandler(cellMouseDown);


public void cellMouseDown(object sender, EventArgs e)
{

  for (int row = 0; row < 9; row++)
  {
    for (int col = 0; col < 9; col++)
    {
       //code to add background color to textbox when selected
    }

  }
}

2 个答案:

答案 0 :(得分:2)

虽然你有其他问题,但它就像这个一样简单

创建时

sc create ServiceTestJarFile binpath="java.exe -cp C:\Selenium\ServerTest.jar;C:\Selenium\Libraries\lib\* com.vzw.uat.dbbackup.emailTest" start=auto type=own error=ignore

点击

for (int row = 0; row < 9; row++)
{
  for (int col = 0; col < 9; col++)
  {
   num += 1;
   cell[row, col] = new TextBox();
   cell[row, col].Name = Convert.ToString(num);
   cell[row, col].MouseDown += new MouseEventHandler(cellMouseDown);
  }
}

其他资源

TextBox.BackColor Property

答案 1 :(得分:0)

为什么需要循环

public void cellMouseDown(object sender, EventArgs e)
{

   var txt = sender as TextBox;
   txt.BackgroundColor = /*to whatever color you want*/
}

你还需要在循环中订阅处理程序:

for (int row = 0; row < 9; row++)
{
  for (int col = 0; col < 9; col++)
  {
   num += 1;
   cell[row, col] = new TextBox();
   cell[row, col].Name = Convert.ToString(num);
   cell[row, col].MouseDown += new MouseEventHandler(cellMouseDown);
  }
}