📜 ⬆️ ⬇️

Exporting tabular data from applications written under .NET in C #

Prehistory


It all started with the fact that he began to write a simple program that was supposed to perform the functions of a telephone directory. As the main component in which all data will be placed, I selected an object of the ListView class. But any good program should be able to save all its data into a separate file, with its subsequent loading, to continue working with data.

In order not to reinvent the wheel, I decided to save the data in an XML file. This type of file is very convenient and popular with many developers, it is easy to work with it. Its only drawback is weak data security. It can be opened with any simple text editor, although you can use text encryption - this does not guarantee complete security for the information in the file.

How to export data?


image
')
As you can see from the screenshot, in the menu item "File" everything is already prepared for the export and import of our phone book, it remains to write the code itself.

When writing this program, I have not yet had any practical experience with XML files in C # under the .NET platform. Therefore, I began to look for material on the Internet. But all my search results were not comforting. All the results found gave a very rough and macaroni code that can be adapted to suit your needs. However, it is still not practical. This code is not easily possible to use in different projects.

After that, I decided to delve into the very feature of working with XML files in C #.

Adaptive code


I turned my attention to the textbook on the C # language, written by Mikhail Flenov, " Bible C #. 2nd edition ". In his book, the author often recommends and insists on the full use of classes. And in the topic of working with XML-files, in order to export and import this one uses “corresponding” methods, which are the methods of the class of the object with which it works.

This method is very good, provided that we personally write the class of the object with which we will work. And what about when we use a ready-made class? For example, the ListView or Datagridview class , we did not write them (personally), but many of us use them often.

At this moment, I realized that I need to create my own class, which I can always use. So I do not need (in the future) to spend all the time on describing various parameters. You just need to override the class methods, or just make edits.

XML class


XML class code
public class Stroka { public void Main(string el1, string el2, string el3, string el4) { El1 = el1; El2 = el2; El3 = el3; El4 = el4; } public string El1 { get; set; } public string El2 { get; set; } public string El3 { get; set; } public string El4 { get; set; } public void SaveToFile(XmlTextWriter xmlOut) { xmlOut.WriteStartElement(""); xmlOut.WriteAttributeString("1", El1.ToString()); xmlOut.WriteAttributeString("2", El2.ToString()); xmlOut.WriteAttributeString("3", El3.ToString()); xmlOut.WriteAttributeString("4", El4.ToString()); xmlOut.WriteEndElement(); } public void LoadFromFile(XmlTextReader xmlin) { try { El1 = xmlin.GetAttribute("1"); El2 = xmlin.GetAttribute("2"); El3 = xmlin.GetAttribute("3"); El4 = xmlin.GetAttribute("4"); } catch(Exception) { } } } 


For this class to work, you need to connect two more assemblies:

 using System.IO; using System.Xml; 

I decided to call the class " Stroka ", this is because we will loop through all the rows in our table. Also note that in all parts of the code 4 elements are described. This is intentional. The number of elements must match our number of columns in the table.

Since our class is ready, we can collapse it in our project, and no longer look into it.

Beautiful export (preservation)


Let's not rush to finish our work. And we will write a few more lines of code that will allow us to invoke the save dialog box.

image

We can call this window like this:

Window call code
 private void ToolStripMenuItem_Click(object sender, EventArgs e) { int count = listView1.Items.Count; if (count == 0) { MessageBox.Show(" .  ."); return; } if (filename == "") { SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.Title = ""; fileDialog.Filter = "XML files|*.xml"; if (fileDialog.ShowDialog() != DialogResult.OK) return; filename = fileDialog.FileName; Export(); } } 


As you can see, this is already a method for exporting data to an XML file. But nothing interesting happens here, only the window for export is called, and its path is written to the variable " filename ". This is a regular string variable that is created at the beginning of the project.

It looks like this:

Example
 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Xml; namespace TestPhoneBook { public partial class MainWindow : Form { string filename = ""; public MainWindow() { InitializeComponent(); } ... 


The export itself will be executed in the “Export ();” method.

The time of the method "Export ();"


Export () method code
  public void Export() { //      xml- FileStream fs = new FileStream(filename, FileMode.Create); XmlTextWriter xmlOut = new XmlTextWriter(fs, Encoding.Unicode); xmlOut.Formatting = Formatting.Indented; //   xmlOut.WriteStartDocument(); xmlOut.WriteComment(" .  "); xmlOut.WriteComment(" :  "); //   xmlOut.WriteStartElement("PhoneBook"); xmlOut.WriteAttributeString("Version", "1.0.0"); //    int count = listView1.Items.Count; for (int t = 0; t < count; t++) { ListViewItem item = listView1.Items[t]; Stroka stroka = new Stroka(); stroka.Main(item.SubItems[0].Text, item.SubItems[1].Text, item.SubItems[2].Text, item.SubItems[3].Text); stroka.SaveToFile(xmlOut); } //     xmlOut.WriteEndElement(); xmlOut.WriteEndDocument(); //   xmlOut.Close(); fs.Close(); } 


It is important to note that most of this code is “template”, for many of our projects with this class, the only distinguishing feature will always be our “loop through all elements”. It will differ depending on which “table” we will export the data from. In this case, the data is taken from the object of the ListView class.

Pay attention to the lines:

 Stroka stroka = new Stroka(); stroka.Main(item.SubItems[0].Text, item.SubItems[1].Text, item.SubItems[2].Text, item.SubItems[3].Text); 

We create an object of class (our) Stroka , and in its method Main we put the elements of the row (our 4 columns).

Export Completed


image

I opened the XML file with Notepad, and we can compare the file structure with our code.

Our class also allows you to import data into our application. We can also edit and do any other work with them as if the data were originally in the program.

But more about that in another publication.

Source: https://habr.com/ru/post/317612/


All Articles