我有一個datagridview,我們將調用dataGridViewExample。Datagridview點擊時導致IndexOutOfRangeException
我的對象(不常見的數據類型是因爲我的數據庫SQLite的是):
class MyObject
{
public Int64 Vnr { get; set; }
public string Name { get; set; }
public Single Price { get; set; }
public int Amount { get; set; }
}
下面是相關代碼:
//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();
}
當MyForm的被調用了.ShowDialog,它顯示了很好,並顯示我的DataGridView示例就好了。正如你可以從代碼中讀取的那樣,ExampleList
最初是空的,所以它只顯示了一個包含4列的空datagridview:Vnr,Name,Price & Amount。如果我在裏面點擊等等,沒有任何反應 - 所以一切都按計劃進行,至今爲止。
每次我打電話給AddtoDataGridViewExample()
它將新對象添加到Datagridview中,並且datagridview會更新,列出迄今爲止添加的所有對象(它們按照計劃再次將它們顯示爲行)。
現在請記住,我剛剛說過,如果您在撥打AddtoDataGridViewExample()
之前點擊了DataGridViewExample
之內沒有任何事情發生? 那麼,在調用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;
哪裏是處理click事件的代碼?通常會發生此異常是因爲您正在處理單擊事件,然後嘗試在沒有選定行時獲取選定的行。選中一行並單擊網格是互斥的。那麼,處理拋出異常的點擊事件的代碼在哪裏呢? – Josh 2009-05-30 16:42:00
我還沒有添加任何事件到dataGridViewExample,那是令人擔憂的部分:(所以如果有的話,它是一些inbuildt事件導致它。 – CasperT 2009-05-30 16:46:30