现在的位置: 首页 > 综合 > 正文

Windows Forms Programming In C# 读书笔记 – 第三章 Dialogs (2)

2013年07月11日 ⁄ 综合 ⁄ 共 2032字 ⁄ 字号 评论关闭
1。Data Validation       如何防止用户输入的非法(格式不正确)数据对我们的程序造成影响呢?当然要对用户的输入作出检验

     可以利用控件的 Validating 事件,加上正则表达式来检验用户输入的格式是否正确。但是这样有个缺点:只有当焦点从一个control移动到另一个时,Validating 事件才会被触发,如果有某个 control 有不合法数据,但是从未得到过焦点,它就不会被检验

    解决方法:在 Form 的 ok 按钮的处理事件中加入验证数据的代码。 GetAllControls()是重要方法,以后会经常出现


// 遍历所有的control,包括子control(比如Group box中的)

// 浅层次的control会先返回,子control较后检查

Control[] GetAllControls() {

      ArrayList allControls 
= new
 ArrayList();

      Queue queue 
= new
 Queue();

      queue.Enqueue(
this
.Controls);


   
while( queue.Count > 0 ) 
{

           Control.ControlCollection controls 
=
 (Control.ControlCollection)queue.Dequeue();

          
if( controls == null || controls.Count == 0 ) continue
;


       
foreach( Control control in controls ) 
{

                allControls.Add(control);

                queue.Enqueue(control.Controls);

           }


       }


      
return (Control[])allControls.ToArray(typeof
(Control));

}



void okButton_Click(object sender, EventArgs e) {

    
// Validate each control manually

      foreach( Control control in GetAllControls() ) {

          
// Validate this control

          control.Focus();

          
if!this.Validate() ) {

               
this.DialogResult = DialogResult.None;

               
break;

          }


      }


}

2。为用户提供帮助(未完成)

    利用ToolTip 以及 ErrorProvider 控件

void LoanApplicationDialog_Load(object sender, EventArgs e) {

  
// Use tooltips to populate the "information provider"

  foreach( Control control in GetAllControls() ) {

    
string toolTip = toolTip1.GetToolTip(control);

    
if( toolTip.Length == 0 ) continue;

    infoProvider.SetError(control, toolTip);

  }


}



void applicantNameTextBox_Validating(object sender, CancelEventArgs e) {

  
string toolTip = toolTip1.GetToolTip((Control)sender);

  
if( ((TextBox)sender).Text.Length == 0 ) {

    
// 当text box未空时,提示错误

    errorProvider.SetError((Control)sender, toolTip);

    infoProvider.SetError((Control)sender, 
null);

    e.Cancel 
= true;

  }


  
else {

    
// Show the info when there is text in the text box

    errorProvider.SetError((Control)sender, null);

    infoProvider.SetError((Control)sender, toolTip);

  }


}

抱歉!评论已关闭.