c# - 无法将 Type1 的对象转换为 Type2?

标签 c# winforms windows-forms-designer

我正在尝试在基于表单的应用程序中验证 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/

相关文章:

c# - 将List <int?>转换为List <int>

c# - 在使用 .NET 4.0 的 x64 位机器上加载资源的静默失败背后的原因是什么?

c# - 在设计器中移动窗体上的控件时,Visual Studio 2012 突然崩溃

c# - 如何禁用 Windows Media Player 中的右键单击

c# - Visual Studio 2013 - 窗体 "Live"预览

c# - 防止 Size 属性在等于默认值时被序列化

c# - 具有多种实现的 .NET Core 3.1 中的依赖注入(inject)

c# - 如何统计XML文档中特定节点的子节点?

c# - “CookieAuthenticationProvider”不包含“SlidingExpiration”的定义。 claim 到期时间

c# - 无法在 Visual Studio 2019 中添加新的 C# Windows 窗体