WishToBePro
WishToBePro

Reputation: 183

A Problem in DataGridView : datagridview seems readonly to user (WinForms)

I have a datagridview in my form. 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)

What's the problem?

Code of fill 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.

Upvotes: 1

Views: 2213

Answers (1)

Chris Ballard
Chris Ballard

Reputation: 3769

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:

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>. This should work, however :)

Upvotes: 3

Related Questions