get current row

Posts   
 
    
chungpn
User
Posts: 39
Joined: 23-Mar-2011
# Posted on: 01-Apr-2011 10:38:52   

I use this code to bind an entitycollection to a bindingsource control dataGridView1.AutoGenerateColumns = true; ExcludeIncludeFieldsList excludedFields = new ExcludeIncludeFieldsList(); excludedFields.Add(CustomerFields.ContactName); excludedFields.Add(CustomerFields.Country);

        // fetch a collection of customers.
        EntityCollection<CustomerEntity> customers = new EntityCollection<CustomerEntity>();
        SortExpression sorter =
            new SortExpression(CustomerFields.CustomerId | SortOperator.Descending);
        using (DataAccessAdapter adapter = new DataAccessAdapter())
        {
           adapter.FetchEntityCollection(customers, null, 0, sorter, null, excludedFields);
           this.bindingSource1.DataSource = customers;
           int i= bindingSource1.Find("CustomerId","WELLI");
          // bindingSource1.Position = i;
           bindingNavigator1.BindingSource.Position = i;
           this.textBox1.DataBindings.Add(new Binding("Text", bindingSource1, "CustomerId", true));

        }

        // textBox1.DataBindings.Add("Text", customers, "CustomerId");
         this.textBox2.DataBindings.Add(new Binding("Text", bindingSource1, "CompanyName", true));
        //companyNameTextBox.DataBindings.Add("Text", _currentCustomer, "CompanyName");
        // contactNameTextBox.DataBindings.Add("Text", _currentCustomer, "ContactName");

         dataGridView1.DataSource = bindingSource1;

Now when I want to get the current row clicked in the data grid with this code:

         DataRowView currentDRV = (DataRowView)bindingSource1.Current;

        object value= currentDRV["CompanyName"].ToString();

I get the error:

Unable to cast object of type 'Northwind.DAL.EntityClasses.CustomerEntity' to type 'System.Data.DataRowView'.

how can I fix this? Many Thks.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 01-Apr-2011 11:31:56   

DataRowView currentDRV = (DataRowView)bindingSource1.Current;

        object value= currentDRV["CompanyName"].ToString();

I get the error:

Unable to cast object of type 'Northwind.DAL.EntityClasses.CustomerEntity' to type 'System.Data.DataRowView'.

Since the bindingSource is bound to an EntityCollection of Type CustomerEntity, then its items are of Type CustomerEntity.

i.e. bindingSource1.Current is a CustomerEntity not a DataRowView.

So you should use the following:

var currentCustomer = (CustomerEntity)bindingSource1.Current;
// Then you can directly use currentCustomer.CompanyName