[英]A Problem in DataGridView : datagridview seems readonly to user (WinForms)
I have a datagridview in my form. 我的表单中有一个datagridview。 It fills by selecting country with cities of country.I have set the property (AllowUsersToAddRow = True) but when i run my project user can't add or edit or delete any row.I checked it.It is not readonly(readonly = false) and It is enable (Enabled = true)
它通过选择国家/地区和国家/地区的城市来填充。我已经设置了属性(AllowUsersToAddRow = True),但是当我运行我的项目时,用户无法添加或编辑或删除任何行。我选中了它。它不是readonly(readonly = false )并启用(Enabled = true)
What's the problem? 有什么问题?
Code of fill datagridview: 填充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};
}
If you find this question useful don't forgot to vote it. 如果您发现此问题有用,请不要忘记投票。
To give a simplified example, if I do the equivalent of your query, such as: 举一个简化的例子,如果我做与您的查询等效的操作,例如:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
dataGridView.DataSource = cities;
I get the same result as you - no option to add new rows, but if I change to BindingList<T>
and set this to AllowNew
it all works: 我得到与您相同的结果-没有添加新行的选项,但是如果我更改为
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;
EDIT - with a solution for your particular example: 编辑-针对您特定示例的解决方案:
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;
}
Note that a) I had to change the anonymous type in the query select into a concrete type City
and also change the IEnumerable<T>
returned by Linq query to an IList<T>
compatible type to create the BindingList<T>
. 请注意,a)我必须将查询选择中的匿名类型更改为具体类型
City
并将Linq查询返回的IEnumerable<T>
更改为IList<T>
兼容类型以创建BindingList<T>
。 This should work, however :) 这应该工作,但是:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.