none
How to Keep Orignal DataTable Source from Changing RRS feed

  • Question

  •  I have Table that have 3 Columns  tow string and one Boolean


    and I have 2 button Restore Original and save New 

    what I need is if I click restore button before save new change all the original Data to return  

    so I  create Global Datable Origenal   then Retrieve certain Information From active Directory into this DataTAble 

      DataTable Origenal ;

    public void CreateMyTable()

    {

    Origenal = new DataTable(); Origenal .Columns.Add("GroupID", typeof(string)); Origenal .Columns.Add("Name", typeof(string)); var column = new DataColumn("flag", typeof(bool)); column.DefaultValue = false; Origenal .Columns.Add(column);

    }


    then Retrieve certain Information From active Directory into this Origenal Table

              
       UserGrupe GetUserGrupe  = new UserGrupe ();
            Origenal = GetUserGrupe .FindOu();


    when I bind the Datable with DataGridView 

    dataGridView1.DataSource =Origenal

    Origenal  DataTable Result

    GroupID      Name         flag

    A_1          AB        True

    A_2          CC          False

    A_3          DD          False


      In the GridView  if I change Data Like 

    Example Origenal  DataTable

    GroupID      Name         flag

    A_1          AB              False

    A_2          CC              True

    A_3          DD              False


    then  click restore button to restore original data

     dataGridView1.DataSource = Origenal;

    The Result is 

    GroupID      Name         flag

    A_1          AB              True

    A_2          CC              True

    A_3          DD              False

    the A_1 flag return to original Value True

    but A_2 flag remain True when the original Value is False

      

    and to keep the Original Table Data I try to Crete new Table 

                DataTable copyTable = new DataTable();
                 copyTable = Origenal;
                dataGridView1.DataSource = copyTable ;


    but still return the same result

    GroupID      Name         flag

    A_1          AB              True

    A_2          CC              True

    A_3          DD              False

    I also tried 

     dataGridView1.DataSource = Origenal.Copy();
     

    still the Same result 

    then I try another solution 

      

       DataTable copyTable = new DataTable();
         copyTable = Origenal.copy();

     dataGridView1.DataSource = copyTable ;


    the result was the original Data I wanted 


    GroupID      Name         flag

    A_1          AB              True

    A_2          CC              False

    A_3          DD              False

    but I did not understand way this happened and if there is another solution 

    also I have another Question how to Disable first tow column in the dataGridView1 from edit 

    not the DataTable 



    • Edited by AnWarZ Wednesday, April 17, 2019 8:42 AM
    Wednesday, April 17, 2019 8:40 AM

All replies

  • Hi

    Thank you for posting here.

    For your question, you want to keep original DataTable source from changing and disable first two columns in the datagridView1 from edit.

    You could try the following code.

     public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
           
            DataTable Origenal=new DataTable();
            public static  DataTable CreateMyTable()
            {
                DataTable table = new DataTable();
                table.Columns.Add("GroupID", typeof(string));
                table.Columns.Add("Name", typeof(string));
                var column = new DataColumn("flag", typeof(bool));
                column.DefaultValue = false;
                table.Columns.Add(column);
                return table;
            }
    
            private void Button1_Click(object sender, EventArgs e)
            {
                UserGrupe GetUserGrupe = new UserGrupe();
                Origenal = GetUserGrupe.FindOu();
                this.dataGridView1.DataSource = Origenal;
                dataGridView1.Columns[0].ReadOnly = true;//disable first column
                dataGridView1.Columns[1].ReadOnly = true;//disable second column
            }
    
    
            public class UserGrupe
            {
                public DataTable FindOu()
                {
                    DataTable newtable = CreateMyTable();
                    newtable.Rows.Add("A_1", "AB", true);
                    newtable.Rows.Add("A_2", "CC", false);
                    newtable.Rows.Add("A_3", "DD", false);
                    return newtable;
    
                }
    
    
            }
        }

    Result:

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, April 17, 2019 9:36 AM
    Moderator
  • The DataTable has this build in. Use RejectChanges() to revert to the state that you define by calling AcceptChanges().
    Wednesday, April 17, 2019 11:54 AM
  • Hello,

    In the following code sample I use JSON.NET to serialize a DataTable, save the JSON data to disk (alternate option is to store the data to a string property, if not null then it can be used to restore).

    using System;
    using System.Data;
    using System.IO;
    using Newtonsoft.Json;
    
    namespace ChangeToYourNamespace
    {
        public class MockedData
        {
            private bool _hasException;
            public bool HasException => _hasException;
            private Exception _exception;
            public Exception LastException; 
    
    
            private readonly string _fileName = 
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "safe.txt");
    
            /// <summary>
            /// Base for creating our DataTable, if the data was coming from
            /// a database table we would not need to do this.
            /// </summary>
            /// <returns></returns>
            private DataTable Create()
            {
                var dt = new DataTable();
    
                dt.Columns.Add(new DataColumn()
                {
                    ColumnName = "id",
                    DataType = typeof(int),
                    AutoIncrement = true,
                    ReadOnly = true
                });
    
                dt.Columns.Add(new DataColumn()
                {
                    ColumnName = "FirstName", DataType = typeof(string)
                });
                dt.Columns.Add(new DataColumn()
                {
                    ColumnName = "LastName", DataType = typeof(string)
                });
    
                return dt;
            }
            /// <summary>
            /// Simulate reading from a data source such as a database table,
            /// xml file etc.
            /// </summary>
            /// <returns></returns>
            public DataTable GetDataTable()
            {
                var dt = Create();
    
                dt.Rows.Add(null, "Karen","Payne");
                dt.Rows.Add(null, "Anne","Winston");
                dt.Rows.Add(null, "Bob","Smith");
                dt.Rows.Add(null, "Pat","Adams");
    
                File.WriteAllText(_fileName, JsonConvert.SerializeObject(dt));
    
                return dt;
            }
            /// <summary>
            /// If we found a copy of our data use it
            /// </summary>
            /// <returns></returns>
            public DataTable Restore()
            {
                var dt = new DataTable();
    
                if (File.Exists(_fileName))
                {
                    try
                    {
                        var data = File.ReadAllText(_fileName);
                        dt = JsonConvert.DeserializeObject<DataTable>(data);
                        dt.Columns["id"].ReadOnly = true;
                    }
                    catch (Exception ex)
                    {
                        _hasException = true;
                        _exception = ex;
                    }
                }
                else
                {
                    dt = Create();
                }
                return dt;
            }
    
        }
    }
    

    Form code

    using System;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Shown += Form1_Shown;
            }
    
            private void Form1_Shown(object sender, EventArgs e)
            {
                var ops = new MockedData();
                dataGridView1.DataSource = ops.GetDataTable();
            }
    
            private void restoreButton_Click(object sender, EventArgs e)
            {
                var ops = new MockedData();
                var dt = ops.Restore();
                if (!ops.HasException)
                {
                    dataGridView1.DataSource = dt;
                }
                else
                {
                    MessageBox.Show($"Failed to restore\n{ops.LastException.Message}");
                }
            }
        }
    }
    

    File

    [
       {
          "id":0,
          "FirstName":"Karen",
          "LastName":"Payne"
       },
       {
          "id":1,
          "FirstName":"Anne",
          "LastName":"Winston"
       },
       {
          "id":2,
          "FirstName":"Bob",
          "LastName":"Smith"
       },
       {
          "id":3,
          "FirstName":"Pat",
          "LastName":"Adams"
       }
    ]


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, April 17, 2019 1:58 PM
    Moderator
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, April 23, 2019 9:23 AM
    Moderator