我创建了一个包含n个实例的计时器应用程序。当我试图运行该应用程序时,它向我显示一条错误,指出“无法将类型为'System.Windows.Forms.Timer'的对象强制转换为'System.Windows.Forms.Button'”
private void button1_Click(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new System.EventHandler(t_Tick);
panel.Add(AddNewPanel());
panelId++;
}
我的t_tick事件代码:
private void t_Tick(object sender, EventArgs e)
{
Button c = (Button)sender;
Class1 t = findButtonByTag(c.Tag.ToString());
if ((minutes == 0) && (hours == 0) && (seconds == 0))
{
timer.Stop();
MessageBox.Show("Times up");
t.totalSeconds.Enabled = true;
t.totalSeconds.Text = "";
//label12.Text = "";
started = true;
t.pause.Enabled = false;
t.start.Text = "Start";
t.time_in_hour.Text = "00";
t.time_in_minutes.Text = "00";
t.time_in_seconds.Text = "00";
}
else
{
//calculating the seconds that are being passed
if (seconds < 1)
{
seconds = 59;
if (minutes == 0)
{
minutes = 59;
if (hours != 0)
hours -= 1;
}
else
{
minutes -= 1;
}
}
else
seconds--;
if (hours < 10)
t.time_in_hour.Text = "0" + hours.ToString();
else
t.time_in_hour.Text = hours.ToString();
if (minutes < 10)
t.time_in_minutes.Text = "0" + minutes.ToString();
else
t.time_in_minutes.Text = minutes.ToString();
if (seconds < 10)
t.time_in_seconds.Text = "0" + seconds.ToString();
else
t.time_in_seconds.Text = seconds.ToString();
}
}
答案 0 :(得分:0)
这是类代码 公共类Class1 { 公共Class1() { this.panel = new System.Windows.Forms.Panel(); this.label1 = new Label(); this.time = new Label(); this.time_in_hour = new Label(); this.time_in_minutes = new Label(); this.time_in_seconds = new Label(); this.colon1 = new Label(); this.colon2 = new Label(); this.start = new Button(); this.totalSeconds = new TextBox(); this.pause = new Button(); this.delete = new Button(); this.countTimers = new Label(); } public Label countTimers {get;组; } public System.Windows.Forms.Panel panel {get;组; } public Label label1 {get;组; } 公共标签时间{get;组; } public label time_in_hour {get;组; } public label time_in_minutes {get;组; } public Label time_in_seconds {get;组; }
public Label colon1 { get; set; }
public Label colon2 { get; set; }
public TextBox totalSeconds { get; set; }
public Button start { get; set; }
public Button pause { get; set; }
public Button delete { get; set; }
}
}
答案 1 :(得分:-1)
Timer
调用t_Tick
事件而不是Button
。使用Timer
作为发件人而不是Button