我们在写窗体的时候,总是会遇到很多判断控件的显示内容是否为空或者清空其显示信息,为了代码的清洁,我们最好把这些重复的内容写到一个单独的类模块里,下面我来说一下我是如何操作的(我以文本框和组合框为例做了一个Demo):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TestEmpty(TextBox1, Label2) Then Exit Sub
If TestEmpty(ComboBox1, Label1) Then Exit Sub
Clear(TextBox1)
Clear(ComboBox1)
End Sub
''' <summary>
''' 清空控件的显示信息
''' </summary>
''' <param name="ctrl">需要清空的控件对象</param>
''' <remarks>2011-4-22 19:19 by dan</remarks>
Private Sub Clear(ByVal ctrl As Control)
If (TypeOf ctrl Is TextBox) Then
ctrl.Text = ""
ElseIf (TypeOf ctrl Is ComboBox) Then
ctrl.Text = ""
CType(ctrl, ComboBox).SelectedIndex = -1
End If
End Sub
''' <summary>
''' 测试控件的显示信息是否为空
''' </summary>
''' <param name="ctrl">需要判断的控件对象</param>
''' <param name="ctrlshow" >判断控件的标签对象</param>
''' <remarks>2011-4-22 19:20 by dan</remarks>
Private Function TestEmpty(ByVal ctrl As Control, ByVal ctrlshow As Control) As Boolean
Dim result As Boolean
If Trim(ctrl.Text) = "" Then
MsgBox(ctrlshow.Text & "不能为空!", vbOKOnly + vbInformation, "提示")
ctrl.Focus()
result = True
Else
result = False
End If
Return result
End Function<!--
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
--><!--
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
-->
注意:清空的时候,一般只有Text属性的只需调用共用控件类的Text属性清空即可,但是对于如组合框这样还需要清空列表框中的选择的信息的,则需要将控件转换其类型然后对相应的属性进行操作
171

被折叠的 条评论
为什么被折叠?



