我正在尝试在基于表单的应用程序中验证 GroupBox
中的一组控件。
我似乎无法将 ComboBox
映射到应用程序以使其识别并生成错误,它只对 TextBox
这样做。
private void groupBox1_Validating(object sender, CancelEventArgs e)
{
foreach (Control control in groupBox1.Controls)
{
string controlType = control.GetType().ToString();
var lst = new List<string>() { "System.Windows.Forms.TextBox" ,"System.Windows.Forms.ComboBox"};
//if (controlType == "System.Windows.Forms.TextBox")
if (lst.Contains(controlType, StringComparer.OrdinalIgnoreCase))
{
TextBox txtBox = (TextBox)control;
ComboBox combo = (ComboBox)control;
if (string.IsNullOrEmpty(txtBox.Text) && string.IsNullOrEmpty(combo.Text))
{
MessageBox.Show(txtBox.Name + " Can not be empty");
}
}
}
}
这是我收到的错误:
Unable to cast object of type 'System.Windows.Forms.ComboBox' to type 'System.Windows.Forms.TextBox'.
最佳答案
在您的代码中,它将任何文本框和任何组合转换为文本框和组合。
您只需要将其转换为原来的样子。
private void groupBox1_Validating(object sender, CancelEventArgs e)
{
foreach (Control control in groupBox1.Controls)
{
if (control is ComboBox)
{
ComboBox combo = (ComboBox)control;
if (string.IsNullOrEmpty(combo.Text)) MessageBox.Show(combo.Name + " Can not be empty");
}
else if (control is TextBox)
{
TextBox txtBox = (TextBox)control;
if (string.IsNullOrEmpty(txtBox.Text)) MessageBox.Show(txtBox.Name + " Can not be empty");
}
}
}
如果组框只有文本框和组合框你也可以这样做:
private void groupBox1_Validating(object sender, CancelEventArgs e)
{
foreach (dynamic control in groupBox1.Controls)
{
if (string.IsNullOrEmpty(control.Text)) MessageBox.Show(control.Name + " Can not be empty");
}
}
关于c# - 无法将 Type1 的对象转换为 Type2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385257/