Click here to Skip to main content
13,804,051 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
i am new in wpf and mvvm i tried to learn to use it first i successes to show a list of my employee class very good but when i want to add a new one ( means a new employee ) it saves an new empty record in the database , i do not know how to get the value from the textboxs. i searched a lot but cannot reach what's my problem , so can i get any help here is my code
MY MODEL CLASS
    public class Employees 
    {

        #region Employee Members

        int _id;
        string _firstname;
        string _address;
        string _lastname;
        string _language;
        string _dob;
        string _nationality;
        string _gender;


        #endregion

        #region Members Properties

        Notify.NotifyUIBase n = new Notify.NotifyUIBase();

        public int ID
        {
            get { return _id; }
            set
            {
                _id = value;
            }
        }

        public string FirstName
        {
            get { return this._firstname; }
            set
            {
                if (value != this._firstname)
                {
                    this._firstname = value;
                    n.RaisePropertyChanged("FirstName");
                }
                
            }
        }

        public string Address
        {
            get { return _address; }
            set
            {
                _address = value;
                n.RaisePropertyChanged("Address");
            }
        }

        public string LastName
        {
            get { return _lastname; }
            set
            {
                _lastname = value;
                n.RaisePropertyChanged("LastName");
            }
        }

        public string Language
        {
            get { return _language; }
            set
            {
                _language = value;
                n.RaisePropertyChanged("Language");
            }
        }

        public string DOB
        {
            get { return _dob; }
            set
            {
                _dob = (value).ToString();
                n.RaisePropertyChanged("DOB");
            }
        }

        public string Nationality
        {
            get { return _nationality; }
            set
            {
                _nationality = value;
                n.RaisePropertyChanged("Nationality");
            }
        }

        public string Gender
        {
            get { return _gender; }
            set
            {
                _gender = value;
                n.RaisePropertyChanged("Gender");
            }
        }

        #endregion

    }

    MY NOTIFY CLASS  
    public class NotifyUIBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }

    MY VIEWMODEL
    public class EditaEmployeesViewModel
    {
        #region Constructor

        public EditaEmployeesViewModel()
        {
            // intiales commands 
            NewEmployeeButton = new RelayCommand(OpenNewEmployee);
            UpdateEmployeeButton = new RelayCommand(UpdateEmployee);
            DeleteEmployeeButton = new RelayCommand(DeleteEmployee);

            SaveNewEmployeeButton = new RelayCommand(SaveNewEmployee);

        }

        #endregion

        #region Variables

        public RelayCommand NewEmployeeButton { get; set; }
        public RelayCommand UpdateEmployeeButton { get; set; }
        public RelayCommand DeleteEmployeeButton { get; set; }
        public RelayCommand SaveNewEmployeeButton { get; set; }

        private Model.Employees _EmployeeRecord;

        #endregion


        public Model.Employees EmployeeRecord
        {
            get
            {
                if (_EmployeeRecord == null)
                    return _EmployeeRecord = new Model.Employees();
                return _EmployeeRecord;
            }
            set
            {
                _EmployeeRecord = value;
                new Notify.NotifyUIBase().RaisePropertyChanged("EmployeeRecord");
            }
        }


        #region Adding New Employee

        #endregion

        #region Command Methods

        void OpenNewEmployee(object parameter)
        {
            View.AddUpdateEmployee aue = new View.AddUpdateEmployee();
            aue.Show();
        }

        void UpdateEmployee(object parameter)
        {

        }

        void DeleteEmployee(object parameter)
        {

        }

        void SaveNewEmployee(object parameter)
        {
            Model.Employees empp = EmployeeRecord;
            DataAccess.EmplyeeDatabaseLayer.InsertEmployee(empp);
        }
        #endregion

        #region get Employee List

        public ObservableCollection<Model.Employees> EmployeeList
        {
            get
            {
                ObservableCollection<Model.Employees> List = new ObservableCollection<Model.Employees>(DataAccess.EmplyeeDatabaseLayer.GetEmployeeFromDataBase());
                return List;
            }
        }
        #endregion
    }

    MY DATABASE CLASS
    public class EmplyeeDatabaseLayer
    {
        public static List<Model.Employees> GetEmployeeFromDataBase()
        {
            string sql = "select * from Employees";

            DataTable dt = DBConnections.SelectQuery(sql);
            var Employee = new List<Model.Employees>();

            foreach (DataRow row in dt.Rows)
            {
                var obj = new Model.Employees()
                {
                    ID = (int)row["id"],
                    FirstName = (string)row["FirstName"],
                    LastName = (string)row["LastName"],
                    DOB = (string)row["DOB"],
                    Gender = (string)row["Gender"],
                    Nationality = (string)row["Nationality"],
                    Language = ((string)row["Language"]),
                    Address = (string)row["Address"]
                };
                Employee.Add(obj);
            }
            return Employee;
        }

        internal static void InsertEmployee(Model.Employees employee)
        {
            try
            {
                string sql = "insert into Employees ([FirstName],[LastName],[Gender],[DOB],[Language],[Nationality],[Address]) values ";
                sql += "('" + employee.FirstName + "','" + employee.LastName + "','" + employee.Gender + "',";
                sql += "'" + employee.DOB + "','" + employee.Language + "','" + employee.Nationality + "'";
                sql += ",'" + employee.Address + "')";
                DBConnections.InserQuery(sql);

                MessageBox.Show("Data Saved Successfully.");
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {

            }
        }

        internal static void UpdateEmployee(Model.Employees employee)
        {
            try
            {
                string sql = "Update Employees set [FirstName]='" + employee.FirstName + "',[LastName]='" + employee.LastName + "',";
                sql += "[Gender] ='" + employee.Gender + "',[DOB]='" + employee.DOB + "',[Language]='" + employee.Language + "',";
                sql += "[Nationality]='" + employee.Nationality + "',[Address]='" + employee.Address + "' where [ID]='" + employee.ID + "'";

                DBConnections.UpdateQuery(sql);

                MessageBox.Show("Data Updated Successfully.");
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {

            }
        }

        internal static void DeleteEmployee(Model.Employees employee)
        {
            try
            {
                string sql = "Delete * from Employees where ID='" + employee.ID + "'";

                DBConnections.DeleteQuery(sql);

                MessageBox.Show("Data Deleted Successfully.");
            }
            catch (SqlException ex)
            {
                throw ex;
            }
            finally
            {

            }
        }
    }
    
<pre lang="text">MY VIEW ( SHOW EMPLOYEES LIST)
    
    <Window x:Class="EditaWPF01.NewTest.View.EmployeePage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:EditaWPF01.NewTest.View"

        xmlns:vm="clr-namespace:EditaWPF01.NewTest.ViewModel"

        mc:Ignorable="d"

        Title="Employees" Height="450" Width="800" 

       WindowStartupLocation="CenterScreen">

    <Window.DataContext>
        <vm:EditaEmployeesViewModel/>
    </Window.DataContext>

    <Grid>
        <GroupBox Header="Employees List" Margin="5">

            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="27"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <ToolBarTray >
                    <ToolBar >
                        <Button  x:Name="tlNewGas" ToolTip="New Gas" VerticalAlignment="Center" Padding="0" 

                                 Command="{Binding NewEmployeeButton}">
                            <Image Source=".\Pics\File_20px.png" />
                        </Button>
                        <Separator/>
                        <Button  x:Name="tlUpdateGas" ToolTip="Update Gas" VerticalAlignment="Center" Padding="0" 

                                 Command="{Binding UpdateEmployeeButton}">
                            <Image Source=".\Pics\Edit File_20px.png"/>
                        </Button>
                        <Separator/>
                        <Button x:Name="btnDelete" ToolTip="Delete Gas" VerticalAlignment="Center" Padding="0" 

                                Content="Delete" Command="{Binding DeleteEmployeeButton}"/>


                    </ToolBar>
                </ToolBarTray>
                <DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding EmployeeList}" CanUserAddRows="False">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="F.Name" Binding="{Binding Path=FirstName}"/>
                        <DataGridTextColumn Header="L.Name" Binding="{Binding LastName}"/>
                        <DataGridTextColumn Header="Address" Binding="{Binding Address}"/>
                        <DataGridTextColumn Header="DOB" Binding="{Binding DOB}"/>
                        <DataGridTextColumn Header="Gender" Binding="{Binding Gender}"/>
                        <DataGridTextColumn Header="Nationality" Binding="{Binding Nationality}"/>
                        <DataGridTextColumn Header="Language" Binding="{Binding Language}"/>
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
        </GroupBox>
    </Grid>
</Window>


    MY FORM TO ADD NEW EMPLOYEE
    <Window x:Class="EditaWPF01.NewTest.View.AddUpdateEmployee"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        xmlns:local="clr-namespace:EditaWPF01.NewTest.View"

        xmlns:vm="clr-namespace:EditaWPF01.NewTest.ViewModel"

        mc:Ignorable="d"

        Title="Add/Update Employee" Height="450" Width="500" WindowStartupLocation="CenterScreen">
    <Window.DataContext>
        <vm:EditaEmployeesViewModel/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="27"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ToolBarTray Background="Orange">
            <ToolBar Background="Orange">
                <Button  x:Name="tlNewGas" ToolTip="New Gas" VerticalAlignment="Center" 

                         Padding="0" Content="Save" Height="27" Command="{Binding SaveNewEmployeeButton}"/>
            </ToolBar>
        </ToolBarTray>

            <Grid Grid.Row="1">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="150"/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>


            <TextBlock Text="First Name :" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" 

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" 

                      Text="{Binding FirstName, UpdateSourceTrigger=Explicit}"/>
                              
            <TextBlock Text="Last Name :" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center"

                         HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" 

                      Text="{Binding LastName, UpdateSourceTrigger=Explicit}"/>

            <TextBlock Text="Address :" Grid.Row="2" Grid.Column="0" VerticalAlignment="Center"

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="2" Grid.Column="1" VerticalAlignment="Center"

                      Text="{Binding Address, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/>

            <TextBlock Text="DOB :" Grid.Row="3" Grid.Column="0" VerticalAlignment="Center"

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="3" Grid.Column="1" VerticalAlignment="Center"

                      Text="{Binding DOB, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/>

            <TextBlock Text="Language :" Grid.Row="4" Grid.Column="0" VerticalAlignment="Center"

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="4" Grid.Column="1" VerticalAlignment="Center"

                      Text="{Binding Language, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/>

            <TextBlock Text="Nationality :" Grid.Row="5" Grid.Column="0" VerticalAlignment="Center"

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="5" Grid.Column="1" VerticalAlignment="Center"

                      Text="{Binding Nationality, BindingGroupName=Group1, UpdateSourceTrigger=Explicit}"/>

            <TextBlock Text="Gender :" Grid.Row="6" Grid.Column="0" VerticalAlignment="Center"

                       HorizontalAlignment="Center"/>
            <TextBox  Grid.Row="6" Grid.Column="1" VerticalAlignment="Center"

                      Text="{Binding Gender, UpdateSourceTrigger=Explicit}"/>

        </Grid>

    </Grid>
</Window>


What I have tried:

i searched a lot to solve my problem but i can not find a solution , if there is a problem with my code please show me
Posted
Updated 8-Dec-18 18:52pm
Comments
Graeme_Grant 8-Dec-18 19:44pm
   
We are not here to debug your code for you... Have you tried using a debugger to see where your problem is?

What happens when you click the SaveNewEmployeeButton button? Is the data being saved to the database? How are you updating the DataTable linked to the Grid? Is the DataTable holding the new record?

Step through the code and identify where the issue is. Now you know what you need to resolve to fix your issue.

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

As I cannot debug your source code. But consider following points

1. You are creating NotifyBase object in Employees class, which I think is wrong. You need to implement Employees class from INotifyPropertyChanged interface to properly NotifyChange to/from UI. In your case derive Employee class from NotifyUIBase (which already implements NotifyPropertyChanged).

2. Do the same with EditaEmployeeViewModel. derive from NotifyUIBase.
3. Normally for textBox UpdateSourceTrigger is set as PropertyChanged. Because you want to update your VM as soon as you lost focus from textbox. (TextBox PropertyChange is invoked when focus is lost). Make sure UpdateSourceTrigger = explicit is wrking for you
  Permalink  
Comments
Ramy82 10-Dec-18 12:30pm
   
i tried UpdateSourceTrigger = explicit but it store an empty new record in the database
M.Kamran Asim 10-Dec-18 15:04pm
   
Try updatesourcerrigger = propertychanged

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.181218.1 | Last Updated 8 Dec 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100