当所有行的高度超过DataGridview的视觉高度时,DataGridview的ScrollBars会Crash
正如标题所说,
DataGridview.ScrollBars = Vertical;
假设DataGridview的愿景可以包含4行,如果行数达到6,则它有一个Vertical ScrollBar。但如果点击ScrollBar,程序就会崩溃。 如果我们设置DataGridview.ScrollBars = None,就不会出现问题。
public partial class visitorLeave : Form
{
public visitorLeave()
{
InitializeComponent();
}
bool isWorkerStopped = false;
bool clickstart = false;
ManageEmployee me = null;
Thread tr1;
private void visitorLeave_Load(object sender, EventArgs e)
{
me = new ManageEmployee(10);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = me.DataSource;
tr1 = new Thread(new ThreadStart(Add));
tr1.IsBackground = true;
tr1.Start();
}
void Add()
{
while (!isWorkerStopped)
{
if (clickstart)
{
me.AddEmployee(new EmployeeData("new" + DateTime.Now.Ticks.ToString(), "0", "0", "0", "0", "0", null));
dataGridView1.DataSource = me.DataSource;
dataGridView1.UpdateRowHeightInfo(0, true);
clickstart = false;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
clickstart = !clickstart;
}
}
As the title say,
DataGridview.ScrollBars = Vertical;
Assume the vision of DataGridview can contain 4 rows, if the row comes to 6, it has a Vertical ScrollBar. But if click the ScrollBar, the program will crash.
If we set the DataGridview.ScrollBars = None, no problem will happen.
public partial class visitorLeave : Form
{
public visitorLeave()
{
InitializeComponent();
}
bool isWorkerStopped = false;
bool clickstart = false;
ManageEmployee me = null;
Thread tr1;
private void visitorLeave_Load(object sender, EventArgs e)
{
me = new ManageEmployee(10);
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = me.DataSource;
tr1 = new Thread(new ThreadStart(Add));
tr1.IsBackground = true;
tr1.Start();
}
void Add()
{
while (!isWorkerStopped)
{
if (clickstart)
{
me.AddEmployee(new EmployeeData("new" + DateTime.Now.Ticks.ToString(), "0", "0", "0", "0", "0", null));
dataGridView1.DataSource = me.DataSource;
dataGridView1.UpdateRowHeightInfo(0, true);
clickstart = false;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
clickstart = !clickstart;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 Windows 窗体调试逻辑中的漏洞之一,它试图检测您以线程不安全的方式使用控件。它看不到您在 UI 线程以外的线程中分配 DataSource 属性。
使用BackgroundWorker 来实现线程逻辑。并使用其 RunworkerCompleted 事件处理程序来设置网格的 DataSource 属性。或者,如果您希望保留现有的线程代码,请使用 Control.Invoke。
It is one of the leaks in Windows Forms' debugging logic that tries to detect you using controls in a thread-unsafe manner. It cannot see you assigning the DataSource property in a thread other than the UI thread.
Use BackgroundWorker to implement your threaded logic. And use its RunworkerCompleted event handler to set the grid's DataSource property. Or use Control.Invoke if you prefer to keep your existing threading code.