C# 验证表单数据
我正在寻找一种更好的方法来验证表单中没有字段是空白的,目前这是我的实现,如果您有更好的方法,我们欢迎您,注意我使用的是KryptonControlC# 验证表单数据,c#,winforms,verification,C#,Winforms,Verification,我正在寻找一种更好的方法来验证表单中没有字段是空白的,目前这是我的实现,如果您有更好的方法,我们欢迎您,注意我使用的是KryptonControl private bool verify(Control c) { switch (c.GetType().Name) { case "KryptonTextBox": { if (((KryptonTextBox)c).Text == "")
private bool verify(Control c)
{
switch (c.GetType().Name)
{
case "KryptonTextBox":
{
if (((KryptonTextBox)c).Text == "")
{
((KryptonTextBox)c).StateCommon.Border.Color1 = Color.Red;
((KryptonTextBox)c).GotFocus += new EventHandler(ControlGotFocus);
return false;
}
}
break;
case "KryptonComboBox":
{
if (((KryptonComboBox)c).SelectedIndex < 0)
{
((KryptonComboBox)c).StateCommon.ComboBox.Border.Color1 = Color.Red;
((KryptonComboBox)c).GotFocus += new EventHandler(ControlGotFocus);
return false;
}
}
break;
case "KryptonDataGridView":
{
if (((KryptonDataGridView)c).Rows.Count <= 0)
{
((KryptonDataGridView)c).StateCommon.HeaderColumn.Border.Color1 = Color.Red;
((KryptonDataGridView)c).GotFocus += new EventHandler(ControlGotFocus);
return false;
}
}
break;
default:
break;
}
if (c.Controls.Count > 0)
{
foreach (Control cc in c.Controls)
{
if (!verify(cc))
{
return false;
}
}
}
return true;
}
您可以像这样优化代码:
switch (c.GetType().Name) { case "KryptonTextBox": }
致:
TextBox tb=c作为TextBox;
如果(tb!=null)
返回字符串.IsNullOrEmpty(tb.Text);
组合框cb=c作为组合框;
如果(cb!=null)
返回cb.SelectedIndex<0;
等
但我建议对这些问题使用验证器 我推荐Deborah Kurata编写的验证类, 这确实帮助我验证了一个有很多文本框的表单
switch (c.GetType().Name) { case "KryptonTextBox": }
TextBox tb = c as TextBox;
if (tb != null)
return string.IsNullOrEmpty(tb.Text);
ComboBox cb = c as ComboBox;
if (cb != null)
return cb.SelectedIndex < 0;
etc.