2013-05-29 111 views
4

我有一個DataGridView綁定到列表。值顯示很好,當我點擊一個值時,它開始編輯,但是當我按下Enter時,這個改變被忽略了,沒有數據被改變。當我在Value setter中放置一個斷點時,我可以看到它在編輯之後執行,但沒有顯示更改過的數據。我的綁定代碼如下所示:可編輯的DataGridView綁定到列表

namespace DataGridViewList 
{ 
    public partial class Form1 : Form 
    { 
    public struct LocationEdit 
    { 
     public string Key { get; set; } 
     private string _value; 
     public string Value { get { return _value; } set { _value = value; } } 
    }; 

    public Form1() 
    { 
     InitializeComponent(); 
     BindingList<LocationEdit> list = new BindingList<LocationEdit>(); 
     list.Add(new LocationEdit { Key = "0", Value = "Home" }); 
     list.Add(new LocationEdit { Key = "1", Value = "Work" }); 
     dataGridView1.DataSource = list; 
    } 
    } 
} 

該項目是一個基本的Windows窗體項目,在設計人員創建一個DataGrid的列稱爲鍵和值分別設置DataPropertyName以鍵/值。沒有值被設置爲只讀。

有沒有我失蹤的一些步驟?我需要實施INotifyPropertyChanged還是其他?

+1

你能展示一些更多的代碼嗎?例如,像編輯/確認事件處理程序? –

+0

@PiotrJustyna我沒有這樣的處理程序。我必須添加一個嗎? – Suma

+0

發生什麼事情是您的數據網格對基礎列表中的更改一無所知。每次更改該值時,請使用ResetBindings方法(http://msdn.microsoft.com/zh-cn/library/system.windows.forms.control.resetbindings.aspx)通知網格。 –

回答

3

問題是您正在使用struct作爲BindingList項目類型。解決方案是你應該將struct更改爲class,它的工作很好。但是,如果你想繼續使用struct,我有一個想法使它成功,當然它需要更多的代碼,而不是簡單地將struct更改爲class。整個想法是每次單元格的值改變時,底層項目(這是一個結構)應該被分配給一個全新的結構項目。這是您可以用來更改基礎值的唯一方法,否則提交更改後的單元格值將不會更改。我發現,事件CellParsing是一個適用於這種情況下添加自定義代碼,這裏是我的代碼:

namespace DataGridViewList 
{ 
    public partial class Form1 : Form 
    { 
    public struct LocationEdit 
    { 
     public string Key { get; set; } 
     private string _value; 
     public string Value { get { return _value; } set { _value = value; } } 
    }; 

    public Form1() 
    { 
     InitializeComponent(); 
     BindingList<LocationEdit> list = new BindingList<LocationEdit>(); 
     list.Add(new LocationEdit { Key = "0", Value = "Home" }); 
     list.Add(new LocationEdit { Key = "1", Value = "Work" }); 
     dataGridView1.DataSource = list; 
    } 
    //CellParsing event handler for dataGridView1 
    private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e){ 
     LocationEdit current = ((BindingList<LocationEdit>)dataGridView1.DataSource)[e.RowIndex]; 
     string key = current.Key; 
     string value = current.Value; 
     string cellValue = e.Value.ToString() 
     if (e.ColumnIndex == 0) key = cellValue; 
     else value = cellValue; 
     ((BindingList<LocationEdit>)dataGridView1.DataSource)[e.RowIndex] = new LocationEdit {Key = key, Value = value}; 
    } 
    } 
} 

我不認爲這是一個好主意,使用struct這樣保持,class會更好。