2009-05-21 26 views
1

我還沒有用WinForms做過很多工作,所以我想知道有人能否給我一點幫助。我有一個DataGridView綁定到IList <>。當我從集合中刪除選定的記錄(ILIST <>)我得到以下異常:WinForms上的DataGridView在我刪除記錄時拋出異常

「System.IndexOutOfRangeException:索引3不具有價值」

我覺得我的綁定是有點瘸太。所以也許有人可以在這裏給我一個指針。

public Form1() 
    { 
     InitializeComponent(); 
     empGrid.DataSource = stub.GetAllEmplyees(); 
     empGrid.Columns["FirstName"].Visible = true; 
     StatusStrip.Text = "Employee Administration"; 

    } 

我想要做的是刪除一條記錄,然後刷新DataGridGridView。定義要在列中顯示哪些屬性的最佳方法是什麼?

非常感謝!

回答

0

我這樣做,不使用數據源,因爲我必須自定義單元格輸出。

// for inserts 
foreach (var item in data) 
{ 
    DataGridViewRow newRow = new DataGridViewRow(); 
    newRow.CreateCells(myDataGridView, 
     your, 
     data, 
     for, 
     each, 
     cell, 
     here); 
    myDataGridView.Rows.Add(newRow); 
} 

    // for updates 
    myDataGridView.Rows[rowIndex] 
     .SetValues(cell,data,you,wish,to,change,here); 

刪除,我遇到使用沒有問題:

myDataGridView.Rows.RemoveAt(rowIndex); 

myDataGridView.Refresh();應該令人耳目一新的作品。

+0

這正是我需要什麼,我已經填充了我的對象實例集合所以這讓我只是直接綁定到這個列表上,完美..謝謝你,先生! – Nick 2009-05-21 03:11:58

0

考慮使用綁定源(從工具箱拖動它,並設置數據源到您需要的類類型:

public partial class Form1 : Form 
{ 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    List<MyClass> list = new List<MyClass>(); 
    private void Form1_Load(object sender, EventArgs e) 
    { 
     this.bindingSource1.DataSource = typeof(WindowsFormsApplication1.MyClass); 

     list.AddRange(new MyClass[] { 
      new MyClass { Column1 = "1", Column2 = "1" }, 
      new MyClass { Column1 = "2", Column2 = "2" } 
      }); 

     bindingSource1.DataSource = list; 
     bindingSource1.Add(new MyClass { Column1 = "3", Column2 = "3" }); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     //Here you remove rows without taking care of the representation: 
     bindingSource1.RemoveAt(0); 
    } 
} 


class MyClass 
{ 
    public string Column1 { get; set; } 
    public string Column2 { get; set; } 
} 
相關問題