我在单独的线程上查询数据库,并在返回时调用线程安全调用。但是创造了一个例外 - 我做错了什么?
注意我也填充了列表视图但为了清晰起见而将其删除
private void ThreadSafeListView()
{
if (this.listView1.InvokeRequired)
{
try
{
ThreadSafe Operation d = new ThreadSafeOperation(ThreadSafeListView);
this.Invoke(d );
}
catch { }
}
else
{
listView1.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[3].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
listView1.Columns[4].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
}
}
异常细节= InvalidOperationException: “跨线程操作无效:控制'listView1'从其创建的线程以外的线程访问。”
答案 0 :(得分:1)
抛出什么异常?如果它仍然是一个线程安全的异常,那么可能是因为你没有从需要调用的项调用。 尝试:
listView1.Invoke(d)
而不是
this.Invoke(d)
理论上这是表格,所以它应该有效,但如果没有关于例外的更多信息,这是我唯一的猜测。
答案 1 :(得分:0)
我放弃......我只是转动轮子而不是......
void listView1_Resize(object sender, EventArgs e)
{
listView1.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[2].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
listView1.Columns[3].AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
}
答案 2 :(得分:0)
//Here ilv is the List, who's column are to be resized
//Get the current column widths
ArrayList widths = new ArrayList();
foreach (ColumnHeader ch in ilv.Columns)
{
widths.Add(ch.Width);
}
//Get the total width of all the columns
int total_width = 0;
for (int i = 0; i < widths.Count; i++)
{
total_width += (int)widths[i];
}
//Calculate percentages and resize the columns.
for (int i = 0; i < widths.Count; i++)
{
double c_width = (int)widths[i];
double pect = (c_width / total_width);
//get the new width, leave out 25 pixels for scrollbar
double n_width = (ilv.Width - 25) * pect;
n_width = Math.Round(n_width, 0);
//MessageBox.Show(c_width + " - " + pect + " - " + n_width);
ilv.Columns[i].Width = (int)n_width;
}
答案 3 :(得分:0)
你可以这样做:
private void listViewEx_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
e.Cancel = true;
e.NewWidth = 60;
}
答案 4 :(得分:0)
您可以执行以下代码...
首先获取listview onload的值..
然后将它存储在变量中,在ColumnWidthChanging
事件属性中执行此代码,就像这样...
e.cancel = true;
e.NewWidth = // the declared variable in which you store the list view with value in the onload function of the form
示例就像这样
int a = 100;
e.cancel =true;
e.e.NewWidth = a;
就像那样