CBreeze
CBreeze

Reputation: 2965

Databinding and Retrieving Values

I'm currently binding a Company object to a DataGrid that is populated by an OleDB query. Each company has a unique ID, however I do not want to display the Company's IDs in the DataGrid.

I can easily retrieve each Company's Name, which is displayed in the DataGrid, doing something simple such as getting the contents of the selected rows first cell.

However, because the unique ID is not displayed I cannot retrieve the associated Company's ID. Essentially what I would like to achieve is something along the lines of;

MySqlCommand sqlCmd = new MySqlCommand("UPDATE companies SET name = @name, addr1 = @addr1 WHERE CompanyID = @companyID)", sqlCon);

name and addr1 are derived from textboxes that are bound in XAML after a user has selected a company in the DataGrid and clicked an update button. The textboxes are bound by;

<TextBox Text="{Binding SelectedItem.CompanyName, ElementName=dataGrid}" TextWrapping="Wrap" Margin="10" IsReadOnly="true"/>
<TextBox Text="{Binding SelectedItem.CompanyAddr1, ElementName=dataGrid}" Margin="10,0,10,10" Height="26" IsReadOnly="true"/>

I could bind the ID to a TextBox and hide it, however I feel like there is a better way.

Upvotes: 0

Views: 32

Answers (1)

Ghassen
Ghassen

Reputation: 1206

  1. Create a class company :

    public partial class Compay
    {
        public int CompanyID { get; set; }
        public string Name { get; set; }
        public string Addr1 { get; set; }
    }
    
  2. View Model

    public class CompanyVM : ViewModelBase
    {
    
          public CompanyVM()
          {
            CompaySource= getAllCompanies();
          }
    
    
    
         private ObservableCollection<Compay> _compaySource;
         public ObservableCollection<Compay> CompaySource
        {
            get
            {
                return _compaySource;
            }
            set
            {
                _compaySource= value;
                OnPropertyChanged("CompaySource");
            }
        }
    
    }
    

Upvotes: 1

Related Questions