我的表单中有一个datagridview。它通过选择country with country of country来填充。我已经设置了属性(AllowUsersToAddRow = True) 但是当我运行我的项目时,用户无法添加或编辑或删除任何行。我检查了它。它不是只读(readonly = false)并且启用(Enabled = true)
有什么问题?
填充数据格式视图:
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 :(得分: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)我必须将查询选择中的匿名类型更改为具体类型City
,并将Linq查询返回的IEnumerable<T>
更改为IList<T>
兼容类型创建BindingList<T>
。但这应该有效:)