简体   繁体   中英

MahApps DataGrid unable to take user input and write to csv

Any help would be greatly appreciated. Sorry, if my code is junior. I am new to C#.

Problem

I've dynamically create multiple DataGrids in a flyout , using MahApps . The DataGrids are populated by CSV files ( ConvertCSVtoDataTable() ). I want the user to be able to make changes to the DataGrids and when they are done, The DataGrids values will replace the CSV files( UpdateDataGridParameter() ).

UI Tree: Flyout > StackPanel > GroupBox > DataGrid

Issue

DG.SelectAllCells() does not select from the user changed DataGrid . How can I get the VISUAL UI representation of the DataGid or bind the DT property to a data change event. I hope I explained this correctly. If you have any questions that can help me please post and I will respond quickly. Thanks

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace SpiderRoll.Classes
{
    public class DataGridProperties 
    {
        private int IDValue;
        public int ID
        {
            get { return IDValue; }
            set { IDValue = value; }
        }

        private string HeaderValue;
        public string Header
        {
            get { return HeaderValue; }
            set { HeaderValue = value; }
        }

        private string DescriptionValue;
        public string Description
        {
            get { return DescriptionValue; }
            set { DescriptionValue = value; }
        }

        private string NameValue;
        public string Name
        {
            get { return NameValue; }
            set { NameValue = value; }
        }

        private string FilePathValue;
        public string FilePath
        {
            get { return FilePathValue; }
            set { FilePathValue = value; }
        }

        private DataTable DTValue;
        public DataTable DT
        {
            get
            {
                return DTValue;
            }
            set
            {
                DTValue = value;
            }
        }

        public static DataGridProperties DataGridObject(List<DataGridProperties> TBP, int ID = 0, string Name = "")
        {
            foreach (var tb in TBP)
            {
                if (tb.ID == ID || tb.Name == Name)
                {
                    return tb;
                }
            }
            return null;
        }

        public static int FindDataGridID(List<DataGridProperties> DGP, string Name = "")
        {
            int i = 0;
            foreach (var dg in DGP)
            {
                if (dg.Name == Name)
                {
                    return i;
                }
                i++;
            }
            return -1;
        }

        public static GroupBox DataGridPropertieStackPanel(DataGridProperties DataGrid)  // DataGridProperties DataGrid
        {
            GroupBox GB = new GroupBox();
            GB.Header = DataGrid.Header;

            StackPanel SPMain = new StackPanel();
            SPMain.Orientation = System.Windows.Controls.Orientation.Vertical;

            System.Windows.Controls.Label LBDescription = new System.Windows.Controls.Label();
            LBDescription.Content = DataGrid.Description;
            LBDescription.Margin = new Thickness(10, 0, 0, 0);
            SPMain.Children.Add(LBDescription);

            StackPanel SP = new StackPanel();
            SP.Name = DataGrid.Name;
            SP.Orientation = System.Windows.Controls.Orientation.Horizontal;
            SP.Margin = new Thickness(10);

            System.Windows.Controls.DataGrid DG = new System.Windows.Controls.DataGrid();
            DG.Name = DataGrid.Name;
            DG.CanUserAddRows = false;
            DG.ItemsSource = DataGrid.DT.DefaultView;


            SP.Children.Add(DG);
            SPMain.Children.Add(SP);
            GB.Content = SPMain;
            return GB;
        }

        public static DataTable ConvertCSVtoDataTable(string FilePath)
        {
            StreamReader sr = new StreamReader(FilePath);
            string[] headers = sr.ReadLine().Split(',');
            string[] firstLine = sr.ReadLine().Split(',');
            DataTable dt = new DataTable();
            DataColumn column = new DataColumn();
            DataRow fl = dt.NewRow();
            int idx = 0;

            foreach (string header in headers)
            {
                //If bool is in first row, turn the column into a checkbox.
                if (firstLine[idx].ToLower() == "true" || firstLine[idx].ToLower() == "false")
                {
                    column = dt.Columns.Add(header, typeof(bool));
                }
                else
                {
                    column = dt.Columns.Add(header, typeof(string));
                    column.ReadOnly = true;
                }
                if (header.EndsWith("~"))
                {
                    column.ReadOnly = true;
                }
                //Reading and building the first row
                fl[idx] = firstLine[idx];
                idx++;
            }
            //Adding first row
            dt.Rows.Add(fl);

            while (!sr.EndOfStream)
            {
                string line = sr.ReadLine();
                string[] rows = line.Split(',');
                DataRow dr = dt.NewRow();
                for (int i = 0; i < headers.Length; i++)
                {
                    dr[i] = rows[i];
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public static void UpdateDataGridParameter(DataGrid DG)
        {
            StringBuilder sb = new StringBuilder();
            IEnumerable<string> columnNames = DG.Columns.Cast<DataGridColumn>().
                                              Select(column => column.Header.ToString());

            sb.AppendLine(string.Join(",", columnNames));

            DG.UnselectAllCells();
            DG.SelectAllCells();
            foreach (DataRowView row in DG.SelectedItems)
            {
                IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
                sb.AppendLine(string.Join(",", fields));
            }
            DG.UnselectAllCells();
            var filePath = @"C:\IO\" + DG.Name + ".csv";
            File.WriteAllText(filePath, sb.ToString());
        }
    }
}

In Class Bundle, I create a list of DataGrids

    private List<DataGridProperties> dataGridList;
    public List<DataGridProperties> DataGridList
    {
        get
        {
            return dataGridList;
        }
        set
        {
            dataGridList = value;
        }
    }

In Main , I iterate the DataGridlist and populate StackPanels by calling the DataGridPropertieStackPanel function.

                        foreach (var item in bundle.DataGridList)
                        {
                            if (item.Name == DataGrid.Name)
                            {
                                sPanelParameters.Children.Add(DataGridProperties.DataGridPropertieStackPanel(item));
                            }
                        }

Your DataGrid updates the binded DataView once you change the values. You don't have to select and unselect the grid rows, just access the dataview directly. Slightly changed version of your code:

public static void UpdateDataGridParameter(DataGrid dataGrid)
{
    StringBuilder sb = new StringBuilder();
    var dataView = dataGrid.ItemsSource as DataView;
    var columnNames = dataView.Table.Columns
            .Cast<DataColumn>()
            .Select(column => column.ColumnName);

    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRowView row in dataView)
    {
        IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
        sb.AppendLine(string.Join(",", fields));
    }

    var filePath = @"C:\IO\" + dataGrid.Name + ".csv";
    File.WriteAllText(filePath, sb.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM