Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 481787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T01:01:48+00:00 2026-05-13T01:01:48+00:00

I have a wpf window which is used to add as well as edit

  • 0

I have a wpf window which is used to add as well as edit information about an entity.
I am using mvvm architecture and ADO.Net entity model.

The screen looks something like this –

  <!-- EmployeeView -->
  <Window .....DataContext={.....}>

      <WpfToolkit:Datagrid x:Name="dgEmployees"
                           CanUserAddRows="false"
                           ItemSource="{Binding Path=Employees}"
                           ................
                           SelectedItem="{Binding SelectedEmployee}"..>
            <!-3 datagrid template column binding -->              

      </WpfToolkit:Datagrid>

       <TextBox Text="{Binding ElementName=dgEmployees, Path=SelectedEmployee.FirstName}"/>

       <TextBox Text="{Binding ElementName=dgEmployees, Path=SelectedEmployee.LastName}"/>


        <Button Content="Clear" Command="{Binding ClearCommand}"/>
        <Button Content="Save" Command={Binding SaveCommand}">

  </Window>

Here the ClearCommand will simply clear the textboxes and save will add or edit a record. I am setting the DataContext property in the xaml itself. I want to keep the CodeBehind empty.

The ViewModel –

 public class EmployeeViewModel : INotifyProperyChanged
 {
      DatabaseEntities _dbEntities; // Ado.Net Entity model

      RelayCommand _saveCommand, _clearCommand;

      public ObservableCollection<Employee> Employees{get;set;}

      public Employee SelectedEmployee{get; set;}

      public EmployeeViewModel()
      {
           _dbEntities=new DatabaseEntities();
            GetAllEmployees();
      }

      private void GetAllEmployees()
      {
          Employees = new ObservableCollection<Employee>();

          var query = from _e in _dbEntities.Employee
                      select _e;

          foreach(Employee _emp in query)
          {
              Employees.Add(_emp);
          }
      }

      public ICommand SaveCommand
      {
          get
          {
             if(_saveCommand == null)
             {
                 _saveCommand = new RelayCommand(){param => SaveEmployee()};
             }
          }
      }


      public ICommand ClearCommand
      {
          get
          {
             if(_clearCommand == null)
             {
                 _clearCommand = new RelayCommand(){param => Clear()};
             }
          }
      }


      private void Save()
      {
           /*************************Edit****************************/
          // if editing Employee info (this part works fine)


          Employee emp = _dbEntities.Employee.FirstorDefault<Employee>( p => p.EmpID == SelectedEmployee.EmpID);
          if(emp != null)
          {
          .................

          _dbEntities.SaveChanges(true);
           /************************************************************/
           }
           else
           {
           /*******************Add New**************************/
         // if adding new employee info (doesn't work)

         Employee emp = Employee.CreateEmployee(0, SelectedEmployee.FirstName, SelectedEmployee.LastName); // here NullReference Exception is thrown because SelectedEmployee is null while adding a new Employee. 

         _dbEntities.AddToEmployee(emp
         _dbEntities.SaveChanges(true);

          GetAllEmployees();
         /************************************************************/

         }

      }


      private void Clear()
      {
          // to clear all the textboxes before adding new employee info.
          SelectedEmployee = null;
          OnPropertyChanged("SelectedEmployee");
      }
 }

I can edit information, but not add new. If I want to add new Employee info, and enter the FirstName lastname in the respective textboxes. These entered values do not bind with SelectedEmployee property as SelectedEmployee is null( we clear the fields to add a new record). How do I access values entered in the textboxes from SelectedEmployee Property?

I know this problem can be solved by Creating a separate EmployeeModel with the IsSelected property …..But is there any other way out??

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T01:01:48+00:00Added an answer on May 13, 2026 at 1:01 am

    I would recommend you put the FirstName and LastName into strings on the ViewModel, then you always have access to them in the Save method, whether the SelectedEmployee is null or not.

    (In your Save method)

    Employee emp = Employee.CreateEmployee(0, FirstName, LastName);
    

    If you want the textboxes to refresh from the user changing the selected item in the datagrid, you’ll need to override the setter on SelectedEmployee, something like:

        string _firstName;
        public string FirstName 
        {
            get { return _firstName; }
            set
            {
                if (_firstName != value)
                {
                    _firstName = value;
                    OnPropertyChanged("FirstName");
                }
            }
        }
    
        string _lastName;
        public string LastName
        {
            get { return _lastName; }
            set
            {
                if (_lastName != value)
                {
                    _lastName = value;
                    OnPropertyChanged("LastName");
                }
            }
        }
    
        Employee _selectedEmployee;
        public Employee SelectedEmployee
        {
            get { return _selectedEmployee; }
            set
            {
                if (_selectedEmployee != value)
                {
                    _selectedEmployee = value;
                    OnPropertyChanged("SelectedEmployee");
                    FirstName = (_selectedEmployee == null) ? string.Empty : _selectedEmployee.FirstName;
                    LastName = (_selectedEmployee == null) ? string.Empty : _selectedEmployee.LastName;
                }
            }
        }
    

    then simply update your xaml to look like:

       <TextBox Text="{Binding Path=FirstName}"/>
       <TextBox Text="{Binding Path=LastName}"/>
    

    Hope this helps 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.