I have DataGrid that bind a list I have a method of ADD data and I want to let the user delete by chose the row with the mouse and use the delete button
The ADD method can add specific data that choose from Combobox and I don't want to let the user change the data directly by edit cell
I have try to set DataGrid.IsReadOnly = false and DataGridTextColumn.IsReadOnly = true But the delete not work...
To add data I choose data by the Comboboxes and Click Button to execute method: AddNewData
It's doing ok..
How can I do it?
My Relevant DataGrid Named : x:Name="ShiftsGrid"
My Code Behind :
using Shifts.ModelView;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Shifts.Windows
{
/// <summary>
/// Interaction logic for ShiftsManager.xaml
/// </summary>
public partial class ShiftsManager : Window
{
public ShiftsManager()
{
InitializeComponent();
DataContext = new ShiftsManagerMV(Close);
Closing += ((ShiftsManagerMV)DataContext).ShiftsManager_Closing;
}
}
}
All my XAML code
<Window x:Class="Shifts.Windows.ShiftsManager"
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:Shifts.Windows"
mc:Ignorable="d"
Title="ShiftsManager" Height="450" Width="800">
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel Margin="10">
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="5 0 0 0">
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference PositionDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="תיאור עמדה" FontSize="15" />
<TextBox Text="{Binding PositionDescriptionColumnFilter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="15" />
</StackPanel>
</Border>
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference ShiftsTypeDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="סוג משמרת" FontSize="15"/>
<TextBox Text="{Binding ShiftsTypeDescriptionColumnFilter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="15"/>
</StackPanel>
</Border>
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference DaysTypeDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="יום המשמרת" FontSize="15"/>
<TextBox Text="{Binding DaysTypeDescriptionColumnFilter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="15"/>
</StackPanel>
</Border>
</StackPanel>
<DataGrid CanUserDeleteRows="True" IsEnabled="true" FontSize="15" IsReadOnly="False"
x:Name="ShiftsGrid" ItemsSource="{Binding Shifts,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"
BorderBrush="#FF1600F0" AlternatingRowBackground="SkyBlue" AlternationCount="2" SelectionMode="Single" Height="224"
SelectedItem="{Binding CurrentShifts,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Resources>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#FF001389"/>
<Setter Property="Foreground" Value="#CDCCFF"/>
</Style>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<DataTrigger Binding="{Binding Id}" Value="-1">
<Setter Property="Background" Value="#FFFFAE00"/>
<Setter Property="Foreground" Value="#0051ff"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn MinWidth="150" IsReadOnly="True" x:Name="PositionDescriptionColumn" HeaderStringFormat="" Header="מספר עובד" Binding="{Binding Position.Description}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn MinWidth="150" IsReadOnly="True" x:Name="ShiftsTypeDescriptionColumn" HeaderStringFormat="" Header="מספר עובד" Binding="{Binding ShiftsType.Description}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn MinWidth="150" IsReadOnly="True" x:Name="DaysTypeDescriptionColumn" HeaderStringFormat="" Header="מספר עובד" Binding="{Binding DaysType.Description}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<StackPanel >
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" >
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference PositionDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="תיאור עמדה" FontSize="15" />
<ComboBox DisplayMemberPath="{Binding Path=Description}" FontSize="15"
ItemsSource="{Binding Path=Positions}"
SelectedItem="{Binding Path=PositionsToAdd}">
</ComboBox>
</StackPanel>
</Border>
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference ShiftsTypeDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="סוג משמרת" FontSize="15"/>
<ComboBox DisplayMemberPath="{Binding Path=Description}" FontSize="15"
ItemsSource="{Binding Path=ShiftsTypes}"
SelectedItem="{Binding Path=ShiftsTypesToAdd}">
</ComboBox>
</StackPanel>
</Border>
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference DaysTypeDescriptionColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="יום המשמרת" FontSize="15" />
<ComboBox DisplayMemberPath="{Binding Path=Description}" FontSize="15"
ItemsSource="{Binding Path=DaysTypes}"
SelectedItem="{Binding Path=DaysTypesToAdd}">
</ComboBox>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
<Button Content="הוספה" FontSize="20" Command="{Binding AddNewData}" Background="Aquamarine"></Button>
<Button Content="עדכן את נתוני המשמרות" FontSize="25" Background="#FF4FCFFF" Command="{Binding UpdateAllShiftData}" Margin="20"></Button>
</StackPanel>
<StackPanel Margin="10">
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="5 0 0 0">
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference WorkerNumberColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="מספר עובד" FontSize="15" />
<TextBox Text="{Binding WorkerNumberColumnFilter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="15"/>
</StackPanel>
</Border>
<Border BorderThickness="1" BorderBrush="Black" Width="{Binding Source={x:Reference WorkerNameColumn}, Path=ActualWidth}">
<StackPanel>
<TextBlock TextAlignment="Center" Text="שם עובד" FontSize="15"/>
<TextBox Text="{Binding WorkerNameColumnFilter,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="15"/>
</StackPanel>
</Border>
</StackPanel>
<DataGrid x:Name="WorkersGrid" ItemsSource="{Binding Workers,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"
BorderBrush="#FF1600F0" AlternatingRowBackground="SkyBlue" AlternationCount="2" SelectionMode="Single" Height="224" IsReadOnly="True"
SelectedItem="{Binding WorkerRowSelectedRowItem,UpdateSourceTrigger=PropertyChanged}" FontSize="15">
<DataGrid.Resources>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#FF001389"/>
<Setter Property="Foreground" Value="#CDCCFF"/>
</Style>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="DataGridCell.IsSelected" Value="True">
<Setter Property="Background" Value="Yellow" />
<Setter Property="Foreground" Value="Purple" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn MinWidth="150" x:Name="WorkerNumberColumn" HeaderStringFormat="" Header="מספר עובד" Binding="{Binding WorkerNumber}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn MinWidth="150" x:Name="WorkerNameColumn" Header="שם עובד" Binding="{Binding WorkerName}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</StackPanel>
</Grid>
</Window>
My Model code :
using IniFiles;
using MilBatDBModels.Shifts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static DataBaseManager.ShiftsDBManager;
using System;
using System.Windows.Input;
using MilBatDBModels.Common;
using System.Windows;
using CommonWindows;
namespace Shifts.ModelView
{
public class ShiftsManagerMV : INotifyPropertyChanged
{
private Action close;
Dictionary<long, ObservableCollection<ShiftsExt>> TableList;
public ObservableCollection<ShiftsExt> Shifts { get; set; }
public ObservableCollection<Worker> Workers { get; set; }
public Positions PositionsToAdd { get; set; }
public ShiftsType ShiftsTypesToAdd { get; set; }
public DaysType DaysTypesToAdd { get; set; }
public ObservableCollection<Positions> Positions { get; set; }
public ObservableCollection<ShiftsType> ShiftsTypes { get; set; }
public ObservableCollection<DaysType> DaysTypes { get; set; }
public bool Changed;
private ShiftsExt currentShifts;
public ShiftsExt CurrentShifts {
get
{
return currentShifts;
}
set
{
currentShifts = value;
}
}
private Worker workerRowSelectedRowItem;
public Worker WorkerRowSelectedRowItem
{
get { return workerRowSelectedRowItem; }
set {
workerRowSelectedRowItem = value;
UpdateShifts();
}
}
public void ShiftsManager_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (Changed)
{
YesNoWindow yesNoWindow = new YesNoWindow("יש נתונים שלא עודכנו, האם לעדכן אותם בבסיס הנתונים?", "כן", "לא");
yesNoWindow.ShowDialog();
if (yesNoWindow.ResultYes)
{
UpdateAllShiftDataAction();
}
}
}
public ShiftsManagerMV(Action close)
{
Changed = false;
TableList = null;
ShiftsIniManager s = new ShiftsIniManager();
long CurrentShiftsClass = s.GetShiftsLocalClass();
Positions = new ObservableCollection<Positions> (ShiftsDBManagerInstance.GetPositions(CurrentShiftsClass));
ShiftsTypes = new ObservableCollection<ShiftsType>(ShiftsDBManagerInstance.GetShiftsTypes());
DaysTypes = new ObservableCollection<DaysType>(ShiftsDBManagerInstance.GetDaysTypes());
UpdateWorkers();
this.close = close;
}
private void UpdateShifts()
{
if (workerRowSelectedRowItem != null)
{
if (TableList[workerRowSelectedRowItem.ID] == null || TableList[workerRowSelectedRowItem.ID].Any() == false)
{
TableList[workerRowSelectedRowItem.ID] = new ObservableCollection<ShiftsExt>(ShiftsDBManagerInstance.SelectShifts(workerRowSelectedRowItem.ID));
}
Shifts = new ObservableCollection<ShiftsExt>(TableList[workerRowSelectedRowItem.ID].Select(se => se));
}
}
private void UpdateWorkers()
{
ShiftsIniManager s = new ShiftsIniManager();
long _class = s.GetShiftsLocalClass();
Workers = new ObservableCollection<Worker>
(ShiftsDBManagerInstance.SelectWorkers(_class));
if(TableList == null)
{
TableList = new Dictionary<long, ObservableCollection<ShiftsExt>>();
for (int i = 0; i < Workers.Count; i++)
{
TableList.Add(Workers[i].ID, new ObservableCollection<ShiftsExt>());
}
}
}
private string _WorkerNumberColumnFilter;
public string WorkerNumberColumnFilter
{
get
{
return _WorkerNumberColumnFilter;
}
set
{
if (_WorkerNumberColumnFilter != value)
{
_WorkerNumberColumnFilter = value;
RunFilterAction();
}
}
}
private string _WorkerNameColumnFilter;
public string WorkerNameColumnFilter
{
get
{
return _WorkerNameColumnFilter;
}
set
{
if (_WorkerNameColumnFilter != value)
{
_WorkerNameColumnFilter = value;
RunFilterAction();
}
}
}
private void RunFilterAction()
{
UpdateWorkers();
List<Worker> wTemp = Workers.ToList();
if (string.IsNullOrWhiteSpace(_WorkerNumberColumnFilter) == false)
{
wTemp = wTemp.
Where(w => w.WorkerNumber.ToLower().Contains(_WorkerNumberColumnFilter.ToLower())).ToList();
}
if (string.IsNullOrWhiteSpace(_WorkerNameColumnFilter) == false)
{
wTemp = wTemp.
Where(w => w.WorkerName.ToLower().Contains(_WorkerNameColumnFilter.ToLower())).ToList();
}
Workers = new ObservableCollection<Worker>(wTemp);
}
private string _PositionDescriptionColumnFilter;
public string PositionDescriptionColumnFilter
{
get
{
return _PositionDescriptionColumnFilter;
}
set
{
if (_PositionDescriptionColumnFilter != value)
{
_PositionDescriptionColumnFilter = value;
RunFilterShiftsAction();
}
}
}
private string _ShiftsTypeDescriptionColumnFilter;
public string ShiftsTypeDescriptionColumnFilter
{
get
{
return _ShiftsTypeDescriptionColumnFilter;
}
set
{
if (_ShiftsTypeDescriptionColumnFilter != value)
{
_ShiftsTypeDescriptionColumnFilter = value;
RunFilterShiftsAction();
}
}
}
private string _DaysTypeDescriptionColumnFilter;
public string DaysTypeDescriptionColumnFilter
{
get
{
return _DaysTypeDescriptionColumnFilter;
}
set
{
if (_DaysTypeDescriptionColumnFilter != value)
{
_DaysTypeDescriptionColumnFilter = value;
RunFilterShiftsAction();
}
}
}
private void RunFilterShiftsAction()
{
UpdateShifts();
List<ShiftsExt> sTemp = Shifts.ToList();
if (string.IsNullOrWhiteSpace(_PositionDescriptionColumnFilter) == false)
{
sTemp = sTemp.
Where(s => s.Position.Description.ToString().ToLower().Contains(_PositionDescriptionColumnFilter.ToLower())).ToList();
}
if (string.IsNullOrWhiteSpace(_ShiftsTypeDescriptionColumnFilter) == false)
{
sTemp = sTemp.
Where(s => s.ShiftsType.Description.ToLower().Contains(_ShiftsTypeDescriptionColumnFilter.ToLower())).ToList();
}
if (string.IsNullOrWhiteSpace(_DaysTypeDescriptionColumnFilter) == false)
{
sTemp = sTemp.
Where(s => s.DaysType.Description.ToLower().Contains(_DaysTypeDescriptionColumnFilter.ToLower())).ToList();
}
Shifts = new ObservableCollection<ShiftsExt>(sTemp);
}
private ICommand _AddNewData;
public ICommand AddNewData
{
get
{
if (_AddNewData == null)
{
_AddNewData = new RelayCommand((param) => AddNewDataAction());
}
return _AddNewData;
}
}
private void AddNewDataAction()
{
Changed = true;
if (Shifts.Where(se=>(se.DaysType.Code == DaysTypesToAdd.Code) && (se.ShiftsType.Code == ShiftsTypesToAdd.Code)).Any())
{
MessageBox.Show("לא ניתן לתת לאותו עובד את אותה משמרת באותו יום");
return;
}
Worker w = workerRowSelectedRowItem;
Shifts.Add(new ShiftsExt(-1,
new Worker(w.ID, w.WorkerNumber, w.WorkerName,w.Address,w.City,w.PhoneNumber,w.PhoneNumber2,w.Number,w.ClassCode),
new Positions(PositionsToAdd.Code, PositionsToAdd.Description, PositionsToAdd.ClassCode),
new ShiftsType(ShiftsTypesToAdd.Code, ShiftsTypesToAdd.Description),
new DaysType(DaysTypesToAdd.Code, DaysTypesToAdd.Description)));
TableList[workerRowSelectedRowItem.ID] = new ObservableCollection<ShiftsExt>(Shifts.Select(se => se));
//ShiftsIniManager s = new ShiftsIniManager();
//for (int i = 0; i < Workers.Count(); i++)
//{
// Workers[i].ClassCode = s.GetShiftsLocalClass();
//}
//List<Worker> wTemp = Workers.ToList();
//wTemp.RemoveAll(w => w.WorkerName == null);
//ShiftsDBManagerInstance.UpdateWorkers(wTemp);
//UpdateWorkers();
}
private ICommand _UpdateAllShiftData;
public ICommand UpdateAllShiftData
{
get
{
if (_UpdateAllShiftData == null)
{
_UpdateAllShiftData = new RelayCommand((param) => UpdateAllShiftDataAction());
}
return _UpdateAllShiftData;
}
}
private void UpdateAllShiftDataAction()
{
for (int i = 0; i < TableList.Count; i++)
{
if (TableList.ElementAt(i).Value.Any()) {
ShiftsDBManagerInstance.UpdateShifts(TableList.ElementAt(i).Value.ToList());
}
}
//ShiftsIniManager s = new ShiftsIniManager();
//for (int i = 0; i < Workers.Count(); i++)
//{
// Workers[i].ClassCode = s.GetShiftsLocalClass();
//}
//List<Worker> wTemp = Workers.ToList();
//wTemp.RemoveAll(w => w.WorkerName == null);
//ShiftsDBManagerInstance.UpdateWorkers(wTemp);
//UpdateWorkers();
MessageBox.Show("השינוי עודכן בהצלחה");
Changed = false;
for (int i = 0; i < Workers.Count(); i++)
{
TableList[Workers[i].ID] = new ObservableCollection<ShiftsExt>(ShiftsDBManagerInstance.SelectShifts(Workers[i].ID));
}
if (TableList[WorkerRowSelectedRowItem.ID].Any())
{
Shifts = new ObservableCollection<ShiftsExt>(TableList[WorkerRowSelectedRowItem.ID].Select(se => se));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}