2016-04-24 138 views
1

好的,这是一个有点棘手的解释。如何知道winform c#中点击了哪个按钮?

我正在研究一个基本的时间表格。

我有7个按钮,名为btnMonTimebtnTueTime依此类推,直到btnSunTime根据星期几。现在,每按一次按钮,弹出一个窗口(winform)打开,让用户通过dateTimePicker控件选择一定的时间。时间被解析为一个字符串并存储。弹出窗口中有一个接受按钮,当按下该按钮时,弹出窗口关闭,并在特定日期旁边显示标注时间的标签。

Image where popup comes up when Time beside Monday is clicked

`Image where label with the time has to be places beside the particular day whose Time button was pressed

现在我知道该怎么做了一个特殊的日子,但事情是,我有一个单一的功能做这个标签制作。但是,如何知道点击哪个时间按钮将其放置在正确的位置?

这是我能想出的代码:

private void btnAccept_Click(object sender, EventArgs e) 
{ 
     formPopup.time = timePicker.Value.ToShortTimeString(); 
     //label1.Text = formPopup.time; 

     Label newLabel = new Label(); 
     newLabel.Text = formPopup.time; 
     newLabel.Location = new System.Drawing.Point(205 + (100 * formTimeTable.CMonTime), 78); 
     formTimeTable.CMonTime++; 
     newLabel.Size = new System.Drawing.Size(100, 25); 
     newLabel.ForeColor = System.Drawing.Color.White; 
     thisParent.Controls.Add(newLabel); 

     this.Close(); 
} 

这是哪个地方的标签,在正确的地方接受按钮单击处理程序。而变量CMonTime记录按下特定按钮的次数。

public static int CMonTime = 0; 
private void btnMonTime_Click(object sender, EventArgs e) 
{ 
    formPopup f2 = new formPopup(); 
    f2.thisParent = this; 
    f2.Show();  
} 

这就是星期一的时间按钮点击处理程序中发生的情况。

但是我怎么能知道哪天的时间按钮实际上被点击以正确放置时间戳标签?

就像星期二的时间按钮被点击一样,时间戳应该显示在星期二的时间按钮旁边。

我试图尽可能清楚。

在此先感谢。

回答

0

sender是引发事件的对象。在你的情况下,它将是用户点击的按钮。

+0

你能详细谈谈那一点吗? –

+0

你不遵循哪一点? – yaakov

2

您可以通过将sender参数强制转换为Button控件来获取单击的按钮。 使用按钮的位置作为一个参数为你的表单为例构造

private void btnMonTime_Click(object sender, EventArgs e) 
{ 
    var button = (Button)sender; 
    formPopup f2 = new formPopup(button.Location); 
    f2.thisParent = this; 
    f2.Show();  
} 

表单为例

Point _buttonLocation; 

public frmPopup(Point buttonLocation) 
{ 
    _buttonLocation = buttonLocation; 
} 

然后使用该按钮的位置来设置标签的位置

private void btnAccept_Click(object sender, EventArgs e) 
{ 
    formPopup.time = timePicker.Value.ToShortTimeString(); 

    Label newLabel = new Label(); 
    newLabel.Text = formPopup.time; 
    newLabel.Location = new Point(_buttonLocation.X + 100, _buttonLocation.Y); 

    formTimeTable.CMonTime++; 
    newLabel.Size = new System.Drawing.Size(100, 25); 
    newLabel.ForeColor = System.Drawing.Color.White; 
    thisParent.Controls.Add(newLabel); 

    this.Close(); 
} 
0

因为控制这些组合重复,创建一个包含所需按钮和标签的用户控件可能会更容易。把UserControl想象成一个由少数几个控件组成的小型表单,然后根据需要将它放置在表单上。它有自己的事件处理程序。这样在技术上只有一个按钮(不是七个)和一个事件处理程序。然后,您可以将该UserControl放置在您的表单上七次。

还有其他一些方法可以避免重复代码,例如有一个事件处理程序并将其分配给所有七个按钮的点击事件。但是,如果你想编辑按钮的布局,UserControl会节省你的时间。你不想这样做七次。

要尝试一下:

  • 添加>新建项目>用户控制。你会得到看起来像一个新的形式。以与将表单添加到控件相同的方式添加一些控件。然后使用名称保存(仅作为示例)MyUserControl.cs
  • 构建项目。
  • 工具箱中将出现一个新的工具箱选项卡,并且您的控件将在那里。
  • 将控件拖到表单上,就像其他任何控件一样。

More info on creating user controls

相关问题