[英]Why i keep getting exception after added checkBoxes in index 0 before column1 in dataGridView1?
[英]Trying to add column to dataGridView1 but getting exception InvalidCastException
在设计器中添加了dataGridView1。 在设计器中,我添加了9列。
然后在form1的构造函数中,我做了:
dataGridView1.Columns.Add(new DataGridViewImageColumn());
dataGridView1.Rows.Add(2);
DataGridViewImageCell cell = (DataGridViewImageCell)dataGridView1.Rows[1].Cells[1];
然后在Form1 Load事件中,我做了:
_thisProcess = Process.GetCurrentProcess().Id;
InitializeRefreshTimer();
PopulateApplications();
然后是定时器的init方法:
void InitializeRefreshTimer()
{
_refreshTimer = new System.Timers.Timer(5000);
_refreshTimer.SynchronizingObject = this;
_refreshTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerToUpdate_Elapsed);
_refreshTimer.Start();
}
然后计时器经过的事件:
void TimerToUpdate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
PopulateApplications();
}
然后是PopulateApplications方法:
void PopulateApplications()
{
dataGridView1.Rows.Clear();
foreach (Process p in Process.GetProcesses())
{
if (p.MainWindowTitle.Length > 1)
{
var icon = Icon.ExtractAssociatedIcon(p.MainModule.FileName);
Image ima = icon.ToBitmap();
String status = p.Responding ? "Running" : "Not Responding";
dataGridView1.Rows.Add(p.MainWindowTitle, status);
cell.Value = ima;
}
}
}
我想要做的是将第一列下单元格中每个进程的所有图标添加到dataGridView1的第一列中。 并且图标应仅显示在每个进程的第一列单元格图标中。
我测试了一下,然后将变量ima保存到了硬盘上,然后我看到那里的图标为图像。 但是我找不到将图标(图像)添加到dataGridView1的方法。
而且我在网上也越来越异常:
DataGridViewImageCell cell = (DataGridViewImageCell)dataGridView1.Rows[1].Cells[1];
无法将类型为“ System.Windows.Forms.DataGridViewTextBoxCell”的对象转换为类型为“ System.Windows.Forms.DataGridViewImageCell”的对象。
System.InvalidCastException was unhandled
HResult=-2147467262
Message=Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell' to type 'System.Windows.Forms.DataGridViewImageCell'.
Source=HardwareMonitoring
StackTrace:
at HardwareMonitoring.Form1..ctor() in Form1.cs:line 132
at HardwareMonitoring.Program.Main() inProgram.cs:line 17
InnerException:
似乎列类型设置不正确:
Unable to cast object of type 'System.Windows.Forms.DataGridViewTextBoxCell'
当您将新列添加到DataGridView
,默认选定的类型是DataGridViewTextBoxColumn
,这将导致DataGridViewTextBoxCell
类型的单元格。 在设计器中编辑列,然后尝试将ColumnType
切换为DataGridViewImageColumn
。 您当前的单元格仅用于文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.