Cas*_*erT 8 c# datagridview winforms
我有一个datagridview,我们将调用dataGridViewExample.
我的对象(不常见的数据类型是因为我的数据库是SQLite):
class MyObject
{
public Int64 Vnr { get; set; }
public string Name { get; set; }
public Single Price { get; set; }
public int Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是相关代码:
//This form gets called with a .ShowDialog(); in my form1.
private List<MyObjecte> ExampleList = new List<MyObject>();
public MyForm()
{
dataGridViewExample.DataSource = OrdreInkøbsListe;
}
private void AddtoDataGridViewExample()
{
//Add a new MyObject to the list
ExampleList.Add(new myObject()
{
Vnr = newVnr,
Amount = newAmount,
Price = newPrice,
Name = newName
});
//refresh datasource
dataGridViewExample.DataSource = null;
dataGridViewExample.Refresh();
dataGridViewExample.DataSource = OrdreInkøbsListe;
ddataGridViewExample.Refresh();
}
Run Code Online (Sandbox Code Playgroud)
当使用.ShowDialog调用MyForm时,它显示正常并显示我的DataGridView示例就好了.正如您可以从代码中读取的ExampleList那样,它最初是空的,因此它只显示一个包含4列的空数据网格视图:Vnr,Name,Price&Amount.如果我在里面点击等没有任何反应 - 所以一切都按计划进行,到目前为止.
每次我调用AddtoDataGridViewExample()它都会将新对象添加到Datagridview,datagridview会更新,列出到目前为止添加的所有对象(它们再次根据计划显示为行).
现在,请记住,我刚刚说过,如果你DataGridViewExample在我打电话之前点击内部没有任何反应AddtoDataGridViewExample()?好吧,在调用AddtoDataGridViewExample()一次或多次后,如果我点击内部程序将崩溃DataGridViewExample(例如:用户想要选择一行).它抛出一个IndexOutOfRangeException并讨论-1索引.它还以另一种形式抛出异常,在我调用MyForm的行上.ShowDialog();
我真的很困惑,你们有什么问题吗?
我唯一的线索是,我确实认为刷新DataGridViewExample数据源可能是导致问题的原因.另一个重要提示:我还没有任何约束的事件对我DataGridViewExample.所以你可以把这个想法排除在外.
这是所有DataGridViewExample的属性:
this.dataGridViewExample.AllowUserToAddRows = false;
this.dataGridViewExample.AllowUserToDeleteRows = false;
this.dataGridViewExample.AllowUserToResizeColumns = false;
this.dataGridViewExample.AllowUserToResizeRows = false;
this.dataGridViewExample.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridViewExample.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewExample.Location = new System.Drawing.Point(591, 53);
this.dataGridViewExample.MultiSelect = false;
this.dataGridViewExample.Name = "dataGridViewExample";
this.dataGridViewExample.ReadOnly = true;
this.dataGridViewExample.RowHeadersVisible = false;
this.dataGridViewExample.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridViewExample.ShowEditingIcon = false;
this.dataGridViewExample.Size = new System.Drawing.Size(240, 150);
this.dataGridViewExample.TabIndex = 31;
Run Code Online (Sandbox Code Playgroud)
Noa*_*Gal 18
我想click事件会尝试获取当前选定的行并对其执行某些操作,同时dataGridViewExample.DataSource = null;清除数据源,并且当前选定的行变为null.
如果DataGridView.DataSource将列表设置为列表,则无需将其重置为空,刷新并再次将其重置为列表(并再次刷新)以查看更改.只需刷新即可DataGridView.
您也可以尝试使用一个BindingList<T>对象而不是一个对象List<T>,它会自动通知您的网格内部更改(添加和删除元素),还有一个INotifyPropertyChanged可以在您的MyObject类上实现的接口,它将使对象中的每个属性都发生变化在网格上显示(对于代码中对象所做的任何更改,而不是通过网格本身).
| 归档时间: |
|
| 查看次数: |
16125 次 |
| 最近记录: |