C# WPF host computer development (membership management software)

[Disclaimer: All rights reserved. Reprinting is welcome. Please do not use it for commercial purposes. Contact email: [email protected]]

        Many students think that the host computer is purely software development and does not involve hardware equipment, such as listening to music, watching movies, writing small applications, etc. If it is consumer electronics, this may indeed be the case. But in addition to consumer electronics and the Internet, PCs may also be involved in industrial production, medical and military fields, and each market segment has a large scale. At this time, the host computer may need to communicate with external devices through USB, can, 232, 485, network and many other cable forms, so the functional margins of the host computer will suddenly expand a lot. In addition, even in the same field, different industries will have different know-hows. Many know-hows are solidified in software logic in the form of software. This is the real competitiveness of the host computer.

        Of course, having said so much, today we still start with simple membership management software. In layman's terms, it is a simple student management system. All files need to be saved in a text, which can usually be considered as json format. After the software is started, the interface can complete the operations of adding, deleting, modifying and checking. Of course, we can say that adding, deleting, modifying and checking is not so high-end, but it is indeed a very basic link in software development.

1. Determine the file saving format, such as data.json

{
  "count": 6,
  "items": [
    {
      "ID": 1,
      "NAME": "aaa"
    },
    {
      "ID": 2,
      "NAME": "bbb"
    },
    {
      "ID": 3,
      "NAME": "ccc"
    },
    {
      "ID": 5,
      "NAME": "ddd"
    },
    {
      "ID": 6,
      "NAME": "eee"
    },
    {
      "ID": 4,
      "NAME": "fff"
    }
  ]
}

        ​​ ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ ​​As shown in the figure above, it contains the basic information of the data, including the amount of data, the ID and NAME of each group of data, etc.

2. Use Newtonsoft.Json library to read and write json files

        We decided to read and write files in json format earlier. The next problem we need to face is how to parse and save the data. Fortunately, NuGet can directly parse json files through the third-party library Newtonsoft.Json, which makes it very convenient.

3. Design interface

        The design of the interface part is not difficult. It’s a bit simpler to say, but it can be divided into two parts. The left side is the work of adding, deleting, modifying and checking data, and the right side is the display part of all current data. The reason why we add the display content on the right is mainly to visually observe whether there are any problems with our current operation.

        After designing the interface, it is not difficult to convert it into xaml code.

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp"
        mc:Ignorable="d"
        Title="MemberInfo" Height="300" Width="800">
    <Grid>
        <RadioButton x:Name="radio_add" Checked="Add_Checked" Content="add" HorizontalAlignment="Left" Margin="51,44,0,0" VerticalAlignment="Top"/>
        <RadioButton x:Name="radio_del" Checked="Del_Checked" Content="del" HorizontalAlignment="Left" Margin="129,44,0,0" VerticalAlignment="Top"/>
        <RadioButton x:Name="radio_update" Checked="Update_Checked" Content="update" HorizontalAlignment="Left" Margin="194,44,0,0" VerticalAlignment="Top"/>
        <RadioButton x:Name="radio_search" Checked="Search_Checked" Content="search" HorizontalAlignment="Left" Margin="284,44,0,0" VerticalAlignment="Top"/>

        <Label Content="ID:" HorizontalAlignment="Left" Margin="75,97,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="id" HorizontalAlignment="Left" Height="23" Margin="193,97,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
        <Label Content="Name" HorizontalAlignment="Left" Margin="75,134,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="name" HorizontalAlignment="Left" Height="23" Margin="193,138,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.498,2.609"/>

        <Button Content="OK" Click="OK_Click" HorizontalAlignment="Left" Margin="51,202,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Content="Cancel" Click="Cancel_Click" HorizontalAlignment="Left" Margin="157,202,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Content="Save" Click="Save_Click" HorizontalAlignment="Left" Margin="263,202,0,0" VerticalAlignment="Top" Width="75"/>

        <Label Content="Member Details" HorizontalAlignment="Left" Margin="435,38,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="all_data" HorizontalAlignment="Left" Height="146" Margin="435,75,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="315"/>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="235" Margin="395,10,0,0" VerticalAlignment="Top" Width="376"/>
        <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="235" Margin="15,10,0,0" VerticalAlignment="Top" Width="360"/>
    </Grid>
</Window>

        The controls in the software part are all common controls, such as RadioButton, Label, TextBox, and Button. At the same time, in order to distinguish the left and right, we also added an additional Boarder, which is slightly more beautiful.

4. Code writing

        The code as a whole is not difficult. The most important thing is the processing of the OK button, because it needs to determine which operation mode is currently, whether to add or other operation modes. The processing logic of each operating mode is also different. In this part, you can directly view the function content of OK_Click.

        In addition to the processing of the OK button, another important code is the loading and saving of json files. Loading is automatically loaded when the software starts, while saving requires the user to click the Save button to automatically save.

        Finally, you can pay attention to the update_data function. As long as it is a normal operation and the data content changes, this function will be called to update the content in the Textbox.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WpfApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private int select_option = 0;
        private int total = 0;
        private int[] id_array = new int[1000];
        private string[] name_array = new string[1000];

        public MainWindow() // construct function
        {
            InitializeComponent();

            // initialize data
            for(int i = 0; i < 1000;i++)
            {
                id_array[i] = 0;
                name_array[i] = "";
            }

            // load file defined here
            load_file();

            radio_add.IsChecked = true; // set as default value

            //display data here
            all_data.Text = "";
            all_data.IsEnabled = false;
            update_data();
        }

        private void load_file()
        {
            string jsonfile = "data.json";
            JObject jObject;
            JToken items;

            // parse script file
            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonfile))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jObject = (JObject)JToken.ReadFrom(reader);
                }
            }

            // fetch data from json script
            total = Convert.ToInt32(jObject["count"].ToString());
            if(total <= 0)
            {
                return;
            }

            items = jObject["items"];
            if(items == null)
            {
                return;
            }

            // fetch each data
            for (int i = 0; i < total; i ++)
            {
                int id = Convert.ToInt32(items[i]["ID"].ToString());
                string name = items[i]["NAME"].ToString();

                id_array[i] = id;
                name_array[i] = name;
            }
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            int id_val;
            string name_val = name.Text;
            int i = 0;
            int j = 0;

            if (id.Text == "")
            {
                MessageBox.Show("ID input should not be empty!");
                return;
            }

            id_val = Convert.ToInt32(id.Text);
            if(id_val >= 1000)
            {
                MessageBox.Show("ID should be smaller than 1000!");
                goto Final;
            }

            switch(select_option)
            {
                case 1: //add
                    if(name_val == "")
                    {
                        MessageBox.Show("Name can not be empty!");
                        goto Final;
                    }

                    if (total == 1000)
                    {
                        MessageBox.Show("Array is full!");
                        goto Final;
                    }

                    for (i = 0; i < total; i++)
                    {
                        if(id_array[i] == id_val)
                        {
                            MessageBox.Show("Find same id!");
                            goto Final;
                        }
                    }

                    id_array[total] = id_val;
                    name_array[total] = name_val;
                    total += 1;
                    MessageBox.Show("Add successfully!");
                    break;

                case 2://del
                    if (total == 0)
                    {
                        MessageBox.Show("Array is empty!");
                        goto Final;
                    }

                    for (i = 0; i < total; i++)
                    {
                        if (id_array[i] == id_val)
                        {
                            break;
                        }
                    }

                    if(i == total)
                    {
                        MessageBox.Show("Failed to find relevant id!");
                        goto Final;
                    }
                    
                    for(j = i+1; j < total; j++)
                    {
                        id_array[j - 1] = id_array[j];
                        name_array[j - 1] = name_array[j];
                    }
                    total -= 1;
                    MessageBox.Show("Del successfully!");
                    break;

                case 3://update
                    if (name_val == "")
                    {
                        MessageBox.Show("Name can not be empty!");
                        goto Final;
                    }

                    if (total == 0)
                    {
                        MessageBox.Show("Array is empty!");
                        goto Final;
                    }

                    for (i = 0; i < total; i++)
                    {
                        if (id_array[i] == id_val)
                        {
                            break;
                        }
                    }

                    if (i == total)
                    {
                        MessageBox.Show("Failed to find relevant id!");
                        goto Final;
                    }

                    name_array[i] = name_val;
                    MessageBox.Show("Update successfully!");
                    break;

                case 4://search
                    if (total == 0)
                    {
                        MessageBox.Show("Array is empty!");
                        goto Final;
                    }

                    for (i = 0; i < total; i++)
                    {
                        if (id_array[i] == id_val)
                        {
                            break;
                        }
                    }

                    if (i == total)
                    {
                        MessageBox.Show("Failed to find relevant id!");
                        goto Final;
                    }

                    MessageBox.Show("Name is " + name_array[i]);
                    break;

                default:
                    break;
            }

            // display data
            update_data();

        Final:
            id.Text = "";
            name.Text = "";
        }

        private void update_data()
        {
            string data_text = "";

            for(int i = 0; i < total;i++)
            {
                data_text += Convert.ToString(id_array[i]);
                data_text += " ";
                data_text += name_array[i];
                data_text += "\n";
            }

            all_data.Text = "";
            all_data.Text = data_text;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Save_Click(object sender, RoutedEventArgs e) // important callback function
        {
            JArray items = new JArray();
            JObject header = new JObject();

            // save to array
            for(int i = 0; i < total; i++)
            {
                JObject jobj = new JObject();
                jobj["ID"] = id_array[i];
                jobj["NAME"] = name_array[i];
                items.Add(jobj);
            }

            // save to header
            header["count"] = total;
            header["items"] = items;

            // save data
            using (System.IO.StreamWriter file = new System.IO.StreamWriter("data.json"))
            {
                file.Write(header.ToString());
            }
            MessageBox.Show("Save successfully!");
        }

        private void Add_Checked(object sender, RoutedEventArgs e)
        {
            select_option = 1; //add
            name.IsEnabled = true;
        }

        private void Del_Checked(object sender, RoutedEventArgs e)
        {
            select_option = 2; //del
            name.Text = "";
            name.IsEnabled = false;
        }

        private void Update_Checked(object sender, RoutedEventArgs e)
        {
            select_option = 3; //update
            name.IsEnabled = true;
        }

        private void Search_Checked(object sender, RoutedEventArgs e)
        {
            select_option = 4; //search
            name.Text = "";
            name.IsEnabled = false;
        }
    }
}

        As for parameter handling, exception handling, and usage habits handling in the code, these parts can only be experienced and understood by everyone themselves. With this code as a foundation, future CRUD codes, that is, addition, deletion, modification, and search operations, cannot escape this category. Moreover, our data is truly saved in json files, and there is no risk of loss. This also allows the developed software to further expand its practicality and reliability.

5. Run the test

        Running the test is relatively simple. Just compile and execute it directly. If nothing happens, you can see the running screen like this. It is slightly different from the previous design.

Guess you like

Origin blog.csdn.net/feixiaoxing/article/details/134825322