任何人都可以帮我解决这个问题,我真的很难弄清楚如何纠正这个错误:
public class ModDataGridView : DataGridView
{
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ModDataGridView dgv2 = new ModDataGridView();
pnl.Controls.Add(dgv2); //pnl is a Panel type
foreach (ModDataGridView item in pnl.Controls)
{
txt.AppendText(item.GetType().ToString());
}
}
}
类型
的未处理异常' System.InvalidCastException'发生在Test.exe
中附加信息:无法投射类型的对象 ' System.Windows.Forms.DataGridView'输入' Test.ModDataGridView'。
答案 0 :(得分:1)
您确定只想添加ModDataGridView
吗?
您可以使用OfType<>()
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ModDataGridView dgv2 = new ModDataGridView();
pnl.Controls.Add(dgv2); //pnl is a Panel type
foreach (ModDataGridView item in pnl.Controls.OfType<ModDataGridView>())
{
txt.AppendText(item.GetType().ToString());
}
}
}
如果您想要所有控件,请使用基类:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ModDataGridView dgv2 = new ModDataGridView();
pnl.Controls.Add(dgv2); //pnl is a Panel type
foreach (Control item in pnl.Controls)
{
txt.AppendText(item.GetType().ToString());
}
}
}
答案 1 :(得分:0)
使用匿名类型var
foreach (var item in pnl.Controls)
{
if(item.GetType() == typeof(ModDataGridView))
{
txt.AppendText(item.GetType().ToString());
}
}