0

我对编程相当陌生,所以如果我没有正确描述所有内容,请和我一起裸露。我试图为员工创建一个TimeCard应用程序,以便能够通过应用程序跟踪他们的工作时间,而不必手动记下他们的工作时间。我有一个体面的数量的文本框,我需要检查。需要帮助清理和恢复点击的文本框

首先,我想检查文本框是否被点击,它将清除当前在该文本框中的值。其次,我想再次检查文本框,如果用户单击了文本框并且没有在文本框(空白文本框)中插入任何值(小时),它将自动将文本返回到0(小时)。

我正在使用'MouseClick'属性来分配所有这些文本框。模式代码的第一部分工作正常。当用户单击该框时,它会清除之前存在的0文本,但我无法弄清楚如何返回该0值。一旦文本框被点击,它将清除文本框并将其保留为空。我已经看到了可以一次完成一个的方法,但我正在尝试学习如何有效地进行编码。任何关于这种情况的指导和帮助将不胜感激。谢谢。

工具:C#/的Visual Studio 2012 /的Microsoft SQL 2012

private void MainForm_Load(object sender, EventArgs e) 
    { 
    foreach (Control control1 in this.Controls) 
      { 
      if (control1 is TextBox) 
      { 
       control1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.AllTextBoxes_Click); 
      } 
      } 
    } 

//Mouse Click Clear 
    private void AllTextBoxes_Click(object sender, MouseEventArgs e) 
    { 
     if ((sender is TextBox)) 
     { 
     ((TextBox)(sender)).Text = ""; 
     } 
    } 
+0

我建议使用一个按钮来读取文本框中的值并将其提交给数据库(或任何永久性存储),并且只有在数据正确存储后,才能清除文本框。 – Steve 2014-08-28 14:08:24

+0

我不确定要了解您的要求,但检查控件失去焦点时的事件是... [LostFocus](http://msdn.microsoft.com/zh-cn/library/system.windows.forms .control.lostfocus(v = vs.110)的.aspx)。如果您确实使用它,请考虑使用[GotFocus](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.gotfocus(v = vs.110).aspx)而不是Click为更好的用户体验(如果用户使用标签来集中你的文本框呃?:p) – Kilazur 2014-08-28 14:10:51

+0

请澄清这一点'第二,我想再次检查,如果用户离开文本框并插入任何值的小时它返回到 – djv 2014-08-28 14:14:40

回答

0

如果我理解你的要求,你真正想要的是一个Watermark/Cue banner implementation

但是,由于我可能是monstruosly错误,这里是一个你想要完成的实现。

private void MainForm_Load(object sender, EventArgs e) 
{ 
    foreach (Control c in this.Controls) 
     { 
     if (c is TextBox) 
      { 
       c.GotFocus += deleteContent_GotFocus; // No need for more than that ;) 
       c.LostFocus += restoreContent_LostFocus; 
      } 
     } 
    } 

private void deleteContent_GotFocus(object sender, EventArgs e) 
{ 
    if ((sender is TextBox)) 
    { 
     // Using "as" instead of parenthesis cast is good practice 
     (sender as TextBox).Text = String.Empty; // hey, use Microsoft's heavily verbosy stuff already! :o 
    } 
} 

private void restoreContent_LostFocus(object sender, EventArgs e) 
{ 
    if ((sender is TextBox)) 
    { 
     TextBox tb = sender as TextBox; 
     if (!String.IsNullOrEmpty(tb.text)) // or String.IsNullOrWhiteSpace 
      tb.Text = "0"; 
    } 
} 
+0

谢谢!我得到了我需要的东西。我只是不得不将f(!String.IsNullOrEmpty(tb.text))更改为if(tb.Text ==“”) – 2014-08-28 16:34:19

+0

这看起来很奇怪。基本上,String.IsNullOr [Empty/WhiteSpace]是否已经检查过;此外,最好使用myString.Equals(“”)而不是==“”。考虑接受我的答案,如果它确实解决了你的问题。 – Kilazur 2014-08-28 17:01:20