2011-04-03 36 views
1

我的表單中有一個datagridview。它通過選擇國家與城市country.I已設置屬性(AllowUsersToAddRow = True) 但當我運行我的項目用戶不能添加或編輯或刪除任何row.I檢查它。它不是隻讀(只讀=假)並且它是啓用(Enabled = true)在DataGridView中的一個問題:datagridview似乎只讀給用戶(WinForms)

問題是什麼?

代碼填充的DataGridView的:

private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    dgvCityValues.Enabled = cmbCountryValues.SelectedIndex>=0; 
    if (!dgvCityValues.Enabled) 
    { 
     dgvCityValues.DataSource = null; 
     return; 
    } 

    int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString()); 

    dgvValues.DataSource = from record in Program.dal.Cities(CountryId) select new { record.City}; 
} 

如果你覺得這個問題非常有用不要忘了投它。

+0

我刪除datagridview並創建一個新的但存在的問題! :(:(:( – WishToBePro 2011-04-03 09:21:26

+1

這是winforms?webforms?Wpf?Silverlight? – 2011-04-03 09:37:21

+0

在winforms ............................ – WishToBePro 2011-04-03 09:48:24

回答

3

舉一個簡單的例子,如果我做您的查詢的等價物,如:

var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") }; 
dataGridView.DataSource = cities; 

我得到了相同的結果你 - 沒有選擇要添加新行,但如果我更改爲BindingList<T>這種設置爲AllowNew這一切工作:

var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") }; 
var citiesBinding = new BindingList<City>(cities); 
citiesBinding.AllowNew = true; 

dataGridView.DataSource = citiesBinding; 

編輯 - 爲您具體的例子的解決方案:

private class City 
{ 
    public string Name { get; set; } 
} 

private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    dgvCityValues.Enabled = cmbCountryValues.SelectedIndex >= 0; 
    if (!dgvCityValues.Enabled) 
    { 
     dgvCityValues.DataSource = null; 
     return; 
    } 

    int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString()); 

    var queryResults = from record in Program.dal.Cities(CountryId) select new City { Name = record.City }; 
    var queryBinding = new BindingList<City>(queryResults.ToList()); 
    queryBinding.AllowNew = true; 

    dgvValues.DataSource = queryBinding; 
} 

請注意,a)我必須更改查詢中的匿名類型select into具體類型City並且還將由Linq查詢返回的IEnumerable<T>更改爲IList<T>兼容類型以創建BindingList<T>。這應該工作,但是:)

+0

對不起,System.ComponentModel – 2011-04-03 09:43:25

+0

如何將其轉換爲綁定列表?var query = from Program.dal.Cities(CountryId)中的記錄select new {record.City};' – WishToBePro 2011-04-03 09:47:22

+0

我更新了答案 – 2011-04-03 09:57:21