ok so i am gonna give you some pairs which is related to grids . one is working and one is not so wanna know whats the difference between these logically
1st
GenericSyncfusionDatagrid syncfusionDatagrid = new GenericSyncfusionDatagrid() { Type = Type};
syncfusionDatagrid.Loaded += (sender, e) => { mainWindow.SyncfusionDataGridDynamicLoaded(sender, e, syncfusionDatagrid); };
TabItem newTabItem = new TabItem()
{
Header = statement,
FontSize = 10,
Style = (Style)mainWindow.FindResource("StatementMenuTabItem"),
Content = new Border()
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
Child = syncfusionDatagrid
}
};
mainWindow.StatementTabControl.Items.Add(newTabItem);
newTabItem.IsSelected = true;
2nd
NestedSyncfusionDatagrid nestedSyncfusionDatagrid = new NestedSyncfusionDatagrid() { Type = Type };
nestedSyncfusionDatagrid.Loaded += (sender, e) => { mainWindow.NestedSyncfusionDataGridDynamicLoaded(sender, e, nestedSyncfusionDatagrid); };
TabItem newTabItem = new TabItem()
{
Header = statement,
FontSize = 10,
Style = (Style)mainWindow.FindResource("StatementMenuTabItem"),
Content = new Border()
{
BorderBrush = Brushes.Black,
BorderThickness = new Thickness(1),
Child = nestedSyncfusionDatagrid
}
};
mainWindow.StatementTabControl.Items.Add(newTabItem);
newTabItem.IsSelected = true;
2nd set
public void NestedSyncfusionDataGridDynamicLoaded(object sender, RoutedEventArgs e, NestedSyncfusionDatagrid nestedSyncfusionDatagrid)
{
NestedSyncfusionDatagrid sfDataGrid = sender as NestedSyncfusionDatagrid;
string type = sfDataGrid.Type;
nestedSyncfusionDatagrid.RelationalColumn = StatementTabHashmap.hashmap[type].RelationalColumn;
nestedSyncfusionDatagrid.ByCreditDebitInfos = StatementTabHashmap.hashmap[type].Itemsource;
nestedSyncfusionDatagrid.outerHeaders = StatementTabHashmap.hashmap[type].outerHeaders;
nestedSyncfusionDatagrid.innerHeaders = StatementTabHashmap.hashmap[type].innerHeaders;
}
public void SyncfusionDataGridDynamicLoaded(object sender, RoutedEventArgs e, GenericSyncfusionDatagrid syncfusionDatagrid)
{
GenericSyncfusionDatagrid sfDataGrid = sender as GenericSyncfusionDatagrid;
string type = sfDataGrid.Type;
syncfusionDatagrid.headers = StatementTabHashmap.hashmap[type].outerHeaders;
syncfusionDatagrid.Itemsource = StatementTabHashmap.hashmap[type].Itemsource;
}
3rd set
using System;
using System.Collections.ObjectModel;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using MyWpfApp.Models;
using Syncfusion.Data;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.Windows.Shared;
using Syncfusion.Windows.Tools.Controls;
namespace MyWpfApp.Controls;
public partial class GenericSyncfusionDatagrid
{
//public int transactionsNumber = 40;
// public List Categories=["ATM","RTGS"];
// public List Categories { get; set; } = new List { "ATM", "RTGS", };
// public ObservableCollection Categories { get; set; }
public GenericSyncfusionDatagrid(){
headers = [];
reportType = "default";
InitializeComponent();
// Categories = new ObservableCollection<string> { "Category1", "Category2", "Category3" };
this.DataContext = this; // Ensure Categories is available in the DataContext
}
private bool LoadedCounter = false;
public string reportType { get; set; }
private List<object> _Itemsource;
public List<object> Itemsource
{
get { return _Itemsource; }
set { _Itemsource = value; }
}
//public List<object> Itemsource { get; set; }
public string Type { get; set; }
public List<HeaderInfo> headers { get; set; }
public SummaryData summaryData { get; set; }
public void StatementTableContainerLoaded(object sender, RoutedEventArgs e){
if (LoadedCounter)
{
return;
}
addColumns(headers);
//_statementInfos = new List<StatementInfo>();
//int i=0;
//for(i=0;i<20;i++){
// _statementInfos.Add(new StatementInfo(){s_no=i+1,acc_holder_name="SANJEEV KUMAR SO JHABAN SINGH",bank_name="canara bank",account_number="85892200069731",date=new Date(2007,12,26),Narration="Conversion Balance b/f", bparty="CONVERSION BALANCE B F",withdrawal=0,deposit=25000,balance=25000,category="OTHER", domesticOrInternational="Domestic"});
//}
//double totalWithdrawals=0,totalDeposit=0;
//foreach(StatementInfo statementInfo in _statementInfos){
// totalWithdrawals+=(double)statementInfo.withdrawal;
// totalDeposit+=(double)statementInfo.deposit;
// // totalBalance+=(double)statementInfo.balance;
//}
// _statementInfos.Add(new StatementInfo(){s_no=1,acc_holder_name="SANJEEV KUMAR SO JHABAN SINGH",bank_name="canara bank",account_number="85892200069731",date=new Date(2007,12,26),Narration="Conversion Balance b/f"});
// _statementInfos.Add(new StatementInfo(){s_no=2,acc_holder_name="SANJEEV KUMAR SO JHABAN SINGH",bank_name="canara bank",account_number="85892200069731",date=new Date(2007,12,26),Narration="Conversion Balance b/f"});
//_statementInfos.Add(new StatementInfo(){acc_holder_name=$"Transactions: {_statementInfos.Count}",s_no=null, account_number=null,bank_name=null,date=null,Narration=null,bparty=null,withdrawal=totalWithdrawals,balance=null,deposit=totalDeposit,category=null,domesticOrInternational=null,VisibilityState="Collapsed"});
dataGrid.ItemsSource = Itemsource;
// adding table summary columns
//dataGrid.TableSummaryRows[0].SummaryColumns = new ObservableCollection<ISummaryColumn>();
//dataGrid.TableSummaryRows[0].SummaryColumns.Add(new GridSummaryColumn() { Name = "noOfTransactions", Format = "Transactions: {Count}", MappingName = summaryData.totalTransactionColumnname, SummaryType = SummaryType.CountAggregate });
//dataGrid.TableSummaryRows[0].SummaryColumns.Add(new GridSummaryColumn() { Format = "{Sum}", MappingName = summaryData.depositColumnname, SummaryType = SummaryType.DoubleAggregate });
//dataGrid.TableSummaryRows[0].SummaryColumns.Add(new GridSummaryColumn() { Format = "{Sum}", MappingName = summaryData.withdrawalColumnname, SummaryType = SummaryType.DoubleAggregate });
if (summaryData!=null)
{
dataGrid.TableSummaryRows.Add(new GridTableSummaryRow()
{
ShowSummaryInRow = false,
SummaryColumns = new ObservableCollection<ISummaryColumn>()
{
new GridSummaryColumn()
{
Name = "noOfTransactions", Format = "Transactions: {Count}", MappingName = summaryData.totalTransactionColumnname, SummaryType = SummaryType.CountAggregate
},
new GridSummaryColumn()
{
Name="totalDeposit", Format = "{Sum:n}", MappingName = summaryData.depositColumnname, SummaryType = SummaryType.DoubleAggregate
},
new GridSummaryColumn()
{
Name="totalWithdrawal", Format = "{Sum:f}", MappingName = summaryData.withdrawalColumnname, SummaryType = SummaryType.DoubleAggregate
},
}
});
}
// following will auto resize columns at runtime for dynamic data
dataGrid.GridColumnSizer.ResetAutoCalculationforAllColumns();
//dataGrid.GridColumnSizer.Refresh();
LoadedCounter = true;
// if (comboBoxColumnConfig != null)
// {
// // Set ItemsSource to the ComboBoxColumn
// comboBoxColumnConfig.ItemsSource = new List<string> { "ATM", "RTGS" };
// }
// comboBoxColumnConfig.ItemsSource= new List<string> { "ATM", "RTGS" };
// comboBoxColumnConfig.HeaderText="sdfasda";
// dataGrid.QueryCoveredRange += dataGrid_QueryCoveredRange;
// dataGrid.Model.CoveredRanges.Add(new CoveredCellInfo(1,3,1,1));
}
public void addColumns(List<HeaderInfo> headers)
{
SfDataGrid grid;
grid = dataGrid;
if (headers == null)
{
return;
}
foreach (var headerInfo in headers)
{
if (headerInfo.datatype == "string")
{
grid.Columns.Add(new GridTextColumn() { HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName });
}
else if (headerInfo.datatype == "number")
{
Style cellStyle = new Style() { TargetType = typeof(GridCell) };
cellStyle.Setters.Add(new Setter(GridCell.BorderBrushProperty, (Brush)(new BrushConverter().ConvertFrom("#dddddd"))));
cellStyle.Setters.Add(new Setter(GridCell.PaddingProperty, new Thickness(0, 5, 0, 5)));
cellStyle.Setters.Add(new Setter(GridCell.BorderThicknessProperty, new Thickness(0, 1, 0, 1)));
// if header text contains withdrawal and is of type number then make it red
if (headerInfo.HeaderText.Contains("withdrawal", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Red));
}
else if (headerInfo.HeaderText.Contains("deposit", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Green));
}
else if (headerInfo.HeaderText.Contains("balance", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, (Brush)this.FindResource("bgPrimary")));
}
else
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Black));
}
grid.Columns.Add(new GridNumericColumn() { NumberDecimalDigits = headerInfo.numberOfDecimalPlaces, HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName, CellStyle = cellStyle });
}
else if (headerInfo.datatype == "datetime")
{
grid.Columns.Add(new GridDateTimeColumn() { HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName });
}
}
//if (reportType == "statement")
//{
// Grid comboboxGrid = new Grid() { };
// DataTemplate cellTemplate = new DataTemplate();
// FrameworkElementFactory frameworkElement = new FrameworkElementFactory(typeof(Grid));
// frameworkElement.SetValue(Children = [new ComboBoxAdv() ])
// //FrameworkElementFactory frameworkElement = new FrameworkElementFactory()
// cellTemplate.VisualTree = frameworkElement;
// GridTemplateColumn gridTemplateColumn = new GridTemplateColumn()
// {
// HorizontalAlignment = HorizontalAlignment = HorizontalAlignment.Left,
// HeaderText = "Category Not Defined",
// MappingName = "categoryNotDefined",
// CellTemplate = cellTemplate,
// };
//}
}
// public void dataGrid_QueryCoveredRange(object sender, GridQueryCoveredRangeEventArgs e)
// {
// int lastRowIndex = dataGrid.View.Records.Count ; // so if length is 20 then at 21st row bcz one is for header too
// int totalTransactionsStartingIndex=0;
// int totalTransactionsEndingIndex=5;
// if (e.RowColumnIndex.RowIndex == lastRowIndex)
// {
// if (e.RowColumnIndex.ColumnIndex >= totalTransactionsStartingIndex && e.RowColumnIndex.ColumnIndex <= totalTransactionsEndingIndex)
// {
// e.Range = new CoveredCellInfo(totalTransactionsStartingIndex,totalTransactionsEndingIndex,lastRowIndex,lastRowIndex);
// e.Handled = true;
// }
// }
// try
// {
// // Debugging: Log the row and column indices to verify the event trigger
// Console.WriteLine($"Row: {e.RowColumnIndex.RowIndex}, Column: {e.RowColumnIndex.ColumnIndex}");
// // Ensure the row index is valid (you want to merge cells in row 2, which is row index 1)
// if (e.RowColumnIndex.RowIndex == 1) // 2nd row (index 1)
// {
// // Ensure the column index is between 1 and 3 (0-based index)
// if (e.RowColumnIndex.ColumnIndex >= 1 && e.RowColumnIndex.ColumnIndex <= 3)
// {
// // Merging columns 1 to 3 (index 1 to 3) in row 2 (index 1)
// e.Range = new Syncfusion.UI.Xaml.Grid.CoveredCellInfo(1, 3, 1, 1);
// e.Handled = true; // Mark event as handled
// }
// }
// }
// catch (Exception ex)
// {
// // Log any exceptions that occur
// Console.WriteLine($"Error in dataGrid_QueryCoveredRange: {ex.Message}");
// }
// }
// public void dataGrid_SelectionChanged(object sender, GridSelectionChangedEventArgs e)
// {
// // Get the selected index of the row
// int selectedRowIndex = dataGrid.SelectedIndex;
// // dataGrid.SelectedIndex=selectedRowIndex;
// for (int i = 0; i < dataGrid.View.Records.Count; i++)
// {
// var row = dataGrid.View.Records[i];
// // Check if the row is selected
// if (i == selectedRowIndex)
// {
// // Apply styles for the selected row (e.g., change background)
// row.Style = new Style(typeof(FrameworkElement));
// row.Style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.LightBlue))); // Selected Row Background
// row.Style.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.White))); // Text Color
// row.Style.Setters.Add(new Setter(FontWeightProperty, FontWeights.Bold)); // Optional: Make text bold
// }
// else
// {
// // Reset default style for non-selected rows
// row.Style = new Style(typeof(FrameworkElement));
// row.Style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Transparent))); // Default Background
// row.Style.Setters.Add(new Setter(ForegroundProperty, new SolidColorBrush(Colors.Black))); // Default Text Color
// }
// }
// If there's a valid selected row index, set it as selected manually
// if (selectedRowIndex >= 0)
// {
// // dataGrid.SelectRow(selectedRowIndex);
// // var rowData = dataGrid.View.GetPropertyAccessProvider().GetRecordAtIndex(selectedRowIndex);
// // dataGrid.SelectedItems.Add(rowData);
// // var record = dataGrid.GetRecordAtRowIndex(selectedRowIndex);
// // dataGrid.SelectedItem = record;
// // Get the actual data (record) corresponding to the selected row index
// var record = _statementInfos[selectedRowIndex]; // Assuming _statementInfos is your data source
// // Add this record to the SelectedItems collection to select the entire row
// dataGrid.SelectedItems.Add(record);
// MessageBox.Show($"{selectedRowIndex}");
// }
// public void dataGrid_QueryCellStyle(object sender, e){
// // Get the selected index of the row
// int selectedRowIndex = dataGrid.SelectedIndex;
// // Check if the current row is the selected row
// if (selectedRowIndex >= 0 && e.RowIndex == selectedRowIndex)
// {
// // Apply the style to the selected row
// e.Style.Background = new SolidColorBrush(Colors.LightBlue); // Set background color
// e.Style.Foreground = new SolidColorBrush(Colors.White); // Set text color (optional)
// }
// else
// {
// // Default style for other rows (optional)
// e.Style.Background = new SolidColorBrush(Colors.Transparent); // Default background
// }
// }
// }
}
using System;
using System.Collections.ObjectModel;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using MyWpfApp.Models;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.Windows.Shared;
namespace MyWpfApp.Controls;
public class HeaderInfo
{
public string HeaderText { get; set; }
public string MappingName { get; set; }
public HorizontalAlignment HorizontalHeaderContentAlignment { get; set; }
public TextAlignment TextAlignment { get; set; }
//valid values : number,string,datetime, template
public string datatype { get; set; }
//for numeric column
public int numberOfDecimalPlaces { get; set; }
public HeaderInfo()
{
numberOfDecimalPlaces = 2;
TextAlignment = TextAlignment.Center;
}
}
public partial class NestedSyncfusionDatagrid
{
//Type like by_credit_debit, by_running_balance
public string Type
{
get { return _Type; }
set { _Type = value; }
}
private string _Type;
public string RelationalColumn { get; set; }
public List<HeaderInfo> outerHeaders { get; set; }
public List<HeaderInfo> innerHeaders { get; set; }
private bool LoadedCounter = false;
// public List<string> Categories=["ATM","RTGS"];
// public List<string> Categories { get; set; } = new List<string> { "ATM", "RTGS", };
// public ObservableCollection<string> Categories { get; set; }
public NestedSyncfusionDatagrid(){
InitializeComponent();
// Categories = new ObservableCollection<string> { "Category1", "Category2", "Category3" };
this.DataContext = this; // Ensure Categories is available in the DataContext
}
//public Type GridDataType { get; set; }
private List<object> _ByCreditDebitInfos;
public List<object> ByCreditDebitInfos
{
get { return _ByCreditDebitInfos; }
set { _ByCreditDebitInfos = value; }
}
public void StatementTableContainerLoaded(object sender, RoutedEventArgs e)
{
}
public void StatementTableLoaded(object sender, RoutedEventArgs e){
//if this is already loaded then dont continue furthur
if (LoadedCounter)
{
return;
}
//MessageBox.Show($"nested grid inside loaded, type: ");
//removing previous ones if any
if (dataGrid.Columns.Count>0)
dataGrid.Columns.Clear();
if (FirstLevelNestedGrid1.Columns.Count > 0)
FirstLevelNestedGrid1.Columns.Clear();
//GridViewDefinition gridViewDefinition = new GridViewDefinition();
//gridViewDefinition.RelationalColumn = "withDrawalInfos";
//gridViewDefinition.DataGrid = new SfDataGrid() { Name= "FirstLevelNestedGrid1", }
//dataGrid.DetailsViewDefinition.ElementAt<GridViewDefinition>(0).DataGrid.Columns.Add();
//if (Type == "by_running_balance")
{
dataGrid.DetailsViewDefinition[0].RelationalColumn = RelationalColumn;
}
//MessageBox.Show($"{outerHeaders.Count}");
addColumns(innerHeaders, "inner");
addColumns(outerHeaders, "outer");
//double totalWithdrawals=0,totalDeposit=0;
//foreach(ByCreditDebitInfo byCreditDebitInfo _ByCreditDebitInfos){
// totalWithdrawals+=(double)byCreditDebitInfo.withdrawal;
// totalDeposit+=(double)statementInfo.deposit;
// // totalBalance+=(double)statementInfo.balance;
//}
// _statementInfos.Add(new StatementInfo(){s_no=1,acc_holder_name="SANJEEV KUMAR SO JHABAN SINGH",bank_name="canara bank",account_number="85892200069731",date=new Date(2007,12,26),Narration="Conversion Balance b/f"});
// _statementInfos.Add(new StatementInfo(){s_no=2,acc_holder_name="SANJEEV KUMAR SO JHABAN SINGH",bank_name="canara bank",account_number="85892200069731",date=new Date(2007,12,26),Narration="Conversion Balance b/f"});
// _statementInfos.Add(new StatementInfo(){acc_holder_name=$"Transactions: {_statementInfos.Count}",s_no=null, account_number=null,bank_name=null,date=null,Narration=null,bparty=null,withdrawal=totalWithdrawals,balance=null,deposit=totalDeposit,category=null,domesticOrInternational=null,VisibilityState="Collapsed"});
dataGrid.ItemsSource = ByCreditDebitInfos;
// following will auto resize columns at runtime for dynamic data
dataGrid.GridColumnSizer.ResetAutoCalculationforAllColumns();
//dataGrid.GridColumnSizer.Refresh();
//dataGrid.GridColumnSizer.Refresh();
LoadedCounter = true;
}
// helper function
//here grid type is 'inner' or 'outer'
public void addColumns(List<HeaderInfo> headers,string gridType)
{
SfDataGrid grid;
if (gridType == "inner")
{
grid = FirstLevelNestedGrid1;
}
else
{
grid = dataGrid;
}
if (headers == null)
{
return;
}
foreach (var headerInfo in headers)
{
if (headerInfo.datatype == "string")
{
grid.Columns.Add(new GridTextColumn() { HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName });
}
else if (headerInfo.datatype == "number")
{
Style cellStyle = new Style() { TargetType = typeof(GridCell) };
cellStyle.Setters.Add(new Setter(GridCell.BorderBrushProperty, (Brush)(new BrushConverter().ConvertFrom("#dddddd"))));
cellStyle.Setters.Add(new Setter(GridCell.PaddingProperty, new Thickness(0, 5, 0, 5)));
cellStyle.Setters.Add(new Setter(GridCell.BorderThicknessProperty, new Thickness(0, 1, 0, 1)));
// if header text contains withdrawal and is of type number then make it red
if (headerInfo.HeaderText.Contains("withdrawal", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Red));
}
else if (headerInfo.HeaderText.Contains("deposit", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Green));
}
else if (headerInfo.HeaderText.Contains("balance", StringComparison.CurrentCultureIgnoreCase))
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, (Brush)this.FindResource("bgPrimary")));
}
else
{
cellStyle.Setters.Add(new Setter(GridCell.ForegroundProperty, Brushes.Black));
}
grid.Columns.Add(new GridNumericColumn() { NumberDecimalDigits = headerInfo.numberOfDecimalPlaces, HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName, CellStyle = cellStyle });
}
else if (headerInfo.datatype == "datetime")
{
grid.Columns.Add(new GridDateTimeColumn() { HeaderText = headerInfo.HeaderText, HorizontalHeaderContentAlignment = headerInfo.HorizontalHeaderContentAlignment, TextAlignment = headerInfo.TextAlignment, MappingName = headerInfo.MappingName });
}
}
}
}