Search code examples
c#wpfdatagridselecteditem

C# WPF MVVMLight get selecteditem from datagrid in textbox


I have a big problem to get the values from Datagrid selected row to the textboxes. The user should select one row and the view should get the values from the row in the specific textbox. After the user can make changes inside the textbox and update the database. After several hours on Youtube tutorials and Google, I still don't have any idea how I can get to the point (Values from the selected row in textbox). Please help me

Below is the Code for View and ViewModel

UserControl:

<!--Database datagrid-->
        <materialDesign:Card Margin="5">
            <DataGrid x:Name="MachineDataGrid" AutoGenerateColumns="False" MaxHeight="750" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding DataContext}">

                <DataGrid.Columns>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgMachineID}" Binding="{Binding MachineID, Mode=TwoWay}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerId}" Binding="{Binding CustomerID}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerName}" Binding="{Binding CustomerName}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCity}" Binding="{Binding City}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCountry}" Binding="{Binding Country}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC1}" Binding="{Binding SpindleC1}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC2}" Binding="{Binding SpindleC2}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHoningHead}" Binding="{Binding HoningHead}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgNCVersion}" Binding="{Binding NCVersion}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHMIVersion}" Binding="{Binding HMIVersion}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHRIVersion}" Binding="{Binding HRIVersion}"/>
                    <materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgAHSVersion}" Binding="{Binding AHSVersion}"/>
                </DataGrid.Columns>
            </DataGrid>
        </materialDesign:Card>

ViewModel:

 //Operation button for save, update, delete and print
    public ICommand SaveCommand { get; private set; }
    public ICommand UpdateCommand { get; private set; }
    public ICommand DeleteCommand { get; private set; }
    public ICommand PrintCommand { get; private set; }
    public ICommand ShowAdvCommand { get; private set; }


    public ObservableCollection<Machine> DataContext { get; set; }
    public Machine MachineSelectedItem { get; set; }
    public object MachineDataGrid { get; private set; }

    //Datagrid string

    //PRWContext for general use
    private PRWContext context = new PRWContext();

    public MachineViewModel()
    {
        //Commands for save, update, delete and print
        SaveCommand = new RelayCommand(() => ExecuteSaveCommand());
        UpdateCommand = new RelayCommand(() => ExecuteUpdateCommand());
        DeleteCommand = new RelayCommand(() => ExecuteDeleteCommand());
        PrintCommand = new RelayCommand(() => ExecutePrintCommand());


        ////Load the data from PRW Database to datagrid
        LoadData();
    }

    private void ExecuteSaveCommand()
    {
        Machine machine = new Machine
        {
            //Machine data
            MachineID = MachineID,
            CustomerID = CustomerID,
            CustomerName = CustomerName,
            City = City,
            Country = Country,

            //Serial data
            SpindleC1 = SpindleC1,
            SpindleC2 = SpindleC2,
            HoningHead = HoningHead,

            //Softwareversion data
            NCVersion = NCVersion,
            HMIVersion = HMIVersion,
            HRIVersion = HRIVersion,
            AHSVersion = AHSVersion
        };

        context.Machines.Add(machine);
        context.SaveChanges();

        ClearText();
    }

    private void ExecuteUpdateCommand()
    {
        Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);

        machine.CustomerID = CustomerID;
        machine.CustomerName = CustomerName;

        context.SaveChanges();
        ClearText();
    }

    private void ExecuteDeleteCommand()
    {
        throw new NotImplementedException();
    }

    private void ExecutePrintCommand()
    {
        throw new NotImplementedException();
    }

    //Load data from database to grid
    private void LoadData()
    {
        context.Machines.Load();
        this.DataContext = context.Machines.Local;
    }

    //Clear textboxes
    private void ClearText()
    {
        MachineID = string.Empty;
        CustomerID = string.Empty;
        CustomerName = string.Empty;
        City = string.Empty;
        Country = string.Empty;
        SpindleC1 = string.Empty;
        SpindleC2 = string.Empty;
        HoningHead = string.Empty;
        NCVersion = string.Empty;
        HMIVersion = string.Empty;
        HRIVersion = string.Empty;
        AHSVersion = string.Empty;
    }

I try to do it with eventrigger for selectionchanged command and several different ways I saw in other questions but I was unlucky : (


Solution

  • I think you are missing one bit of what you have to do in order to get the selected item.

    As you have done, you need to bind (in your XAML code) your DataGrid to your ItemSource. But also, you can use the property SelectdItem

    So, you will end-up having something that looks like this: (I've just included the important bits)

    <DataGrid ItemsSource="{Binding DataContext}"  SelectedItem="{Binding Path=MachineSelectedItem }"/>
    
    

    You can get further explanation on this existent answer but what I've put it should hopefully do the trick ;)