Modify app.config in C#

Hiện giờ thường chỉ những file cấu hình đặc biệt người ta mới sử dụng file xml để cấu hình cho ứng dụng. Với những cấu hình không quá phức tạp thì việc sử dụng appSettings trong file app.config cực kỳ nhanh gọn.

Khai báo biến ‘abc’ có giá trị ‘01/01/1900 00:00:00 AM‘ trong appSettings  trong file app.config:

  1. <?xml version=“1.0”?>
  2. <configuration>
  3. <startup>
  4.   <supportedRuntime version=“v4.0” sku=“.NETFramework,Version=v4.0”/></startup>
  5.   <appSettings>
  6.     <add key=“abc” value=“01/01/1900 00:00:00 AM”/>
  7.   </appSettings>
  8. </configuration>

Để đọc giá trị của abc sử dụng:

  1. string abc = ConfigurationManager.AppSettings[“abc”];

Khi cần thay đổi các giá trị cấu hình này, cách đơn giản nhất là mở file config lên và sửa ^^!. Tuy nhiên đối với những ứng dụng cho người dùng cuối, không thể bắt người dùng tự vào chỉnh sửa được mà ta phải làm chức năng cho họ cấu hình. Dưới đây là một số hàm cần thiết để chỉnh sửa file config.

– Sửa giá trị của biến trong appSettings trong file app.config:

  1. public static void EditAppSetting(string key, string value)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings[key].Value = value;
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

– Thêm 1 giá trị mới vào appSettings trong file app.config:

  1. public static void AddAppSetting(string key, string value)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings.Add(key,value);
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

– Xóa 1 giá trị ra khỏi appSettings trong file app.config:

  1. public static void RemoveAppSetting(string key)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings.Remove(key);
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

Demo thử hàm edit nào:

  1. Console.WriteLine(ConfigurationManager.AppSettings[“abc”]);
  2. EditAppSetting(“abc”,DateTime.Now.ToString());
  3. Console.WriteLine(ConfigurationManager.AppSettings[“abc”]);
  4. Console.ReadLine();

Dòng đầu tiên sẽ in ra giá trị của abc trước khi sửa file config.
Dòng thứ 2 tiến hành sửa giá trị abc thành giá trị thời gian hiện tại trong file config.
Dòng thứ 3 tiến hành đọc lại và in ra giá trị của abc sau khi đã sửa file config.

Chạy lại thêm một lần nữa :

Vậy là xong. Sử dụng app.config nhanh hơn so với thao tác đọc và ghi file xml nhiều đúng không nào.

Note:
– Cần add Reference System.configuration.
– Sau khi chạy chương trình thì file config bị chỉnh sửa là file config trong cùng thư mục chứa file exe (có dạng TenUngDung.exe.config) chứ không phải file app.config trong project đâu nhé.
– Quá trình sửa file config chỉ chính xác khi build ứng dụng ra thành file exe và chạy. Nếu chạy trong chế độ debug thì bị tình trạng là đọc từ file TenUngDung.exe.config nhưng lại ghi ra file TenUngDung.vshost.exe.config.

 

Các hàm tham khảo:

—– Edit value of key
public static void EditAppSetting(string key, string value)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}

—— remove key
public static void RemoveAppSetting(string key)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}

—–Load all key
stackoverflow.com

Export data to excel in C#

  namespace ExportExcel  
    {      
        public partial class ExportDatatabletoExcel : Form  
        {  
            public ExportDatatabletoExcel()  
            {  
                InitializeComponent();  
            }  

            private void Form1_Load(object sender, EventArgs e)
            {

                DataTable dt = new DataTable();

                //Add Datacolumn
                DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));

                dt.Columns.Add("LastName", typeof(String));
                dt.Columns.Add("Blog", typeof(String));
                dt.Columns.Add("City", typeof(String));
                dt.Columns.Add("Country", typeof(String));

                //Add in the datarow
                DataRow newRow = dt.NewRow();

                newRow["firstname"] = "Arun";
                newRow["lastname"] = "Prakash";
                newRow["Blog"] = "http://royalarun.blogspot.com/";
                newRow["city"] = "Coimbatore";
                newRow["country"] = "India";

                dt.Rows.Add(newRow);

                //open file
                StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");

                try
                {

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
                    }

                    wr.WriteLine();

                    //write rows to excel file
                    for (int i = 0; i < (dt.Rows.Count); i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (dt.Rows[i][j] != null)
                            {
                                wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                            }
                            else
                            {
                                wr.Write("\t");
                            }
                        }
                        //go to next line
                        wr.WriteLine();
                    }
                    //close file
                    wr.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

C # – Truyền dữ liệu giữa các Form

Truyền dữ liệu giữa các Window Form rất quan trọng khi làm ví dụ với các hộp thoại . Hoặc đơn giản chỉ là hệ thống đầu vào của nhiều cửa sổ. Trong bài viết này sẽ là 3 cách cơ bản để truyền dữ liệu giữa các Form.

Để đơn giản, chúng ta sẽ truyền một thông điệp dạng text từ một form A sang form B. Form A sẽ có một textbox để nhập thông điệp và một button để gọi form B. Form B sẽ có 1 label để nhận thông điệp.

1. Dùng Contructor

Mọi thứ trong C# đều là class, kể cả Form. Mà class thì luôn có hàm khởi tạo (Contructor). Ta sẽ lợi dụng điều này để truyền tham số vào Form qua Contructor.

Form2 :
Code

Tiếp theo cài đặt trên Form1 :
Code

Khi nhấn nút Send trên Form1, thông điệp trong textbox sẽ được truyền vào tham số của hàm khởi tạo Form2. Nhờ vậy, thông điệp được truyền vào biến _message của Form2.
2. Dùng Properties

Một cách khác để truyền dữ liệu giữa 2 Form là dùng Properties. Trong Form2, ta sẽ khai báo một thuộc tính để lưu giữ thông điệp nhận từ Form1. Khi gọi Form2, Form1 sẽ gán thông điệp trực tiếp vào thuộc tính này.
Form2 :
Code

Form1 :
Code

3. Dùng Delegate

Delegate là một khái niệm khá thú vị và mạnh mẽ trong C#. Nó có rất nhiều ứng dụng và truyền dữ liệu giữa các Form là một trong những ứng dụng đó. Nếu bạn đã từng học qua C++ thì bạn sẽ thấy Delegate cũng tương tự như con trỏ hàm trong C++.

Để thực hiện, trong Form2 ta sẽ khai báo một Delegate có nhiệm vụ nhận vào một tham số và không trả về giá trị. Đồng thời tạo một hàm để lấy tham số của Delegate. Và trong Form1, ta sẽ gọi Delegate này với tham số truyền vào là một chuỗi thông điệp cần gửi.
Form2 :
Code

Form1 :
Code

Trên đây là 3 phương pháp đơn giản nhất để truyền dữ liệu giữa các Form. Hy vọng các bạn sẽ vận dụng tốt các phương pháp này trong chương trình của mình.