Button btn = (Button)sender;报错

Button btn = (Button)sender;报错
我是想打开窗体,循环遍历窗体内所有按钮控件,查询控件名称对应数据库中的值
如果有值就改变颜色,来个(禁用词汇)指点一下

img

img

构造函数里 this.Load += new EventHandler(Button_ColorChange) ,所以 sender 的实际类型是“this”指代的Form,不能强行转换为Button。你想要的效果应该这样写:

private void Button_ColorChange(object sender, EventArgs e)
{
    foreach(Control c in this.Controls)
    {
          if(c.getType().Name == "Button")
           {
              string sql = ............................;
              if(dt.Rows.Count>0)
              {
                  (c as Button).BackColor = Color.Red;
              }
           }
    }

}