Question Saving and reading from a text file

lukaiss

Member
Joined
Jan 18, 2023
Messages
7
Programming Experience
1-3
Hi, I need help please.
I'm doing a project in .net maui that logs cultural events and adds them to a list. I would need help to save the items in the list to a text file .txt when inserting or editing and to load the saved items back when the program is started. I need to use StreamWriter and StreamReader. The "Vložit" button means to insert a new record, the "Upravit" button will insert the modification of the selected item and the "Odstranit" button will delete the selected item.
I will be very happy if you help me :)
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PMA.MainPage">

    <ScrollView>
        <Grid>
            <Grid.ColumnDefinitions>

                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="*"/>

            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>

                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="auto"/>

            </Grid.RowDefinitions>

            <Label Text="Seznam koncertů" FontSize="Medium" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="0"/>
            
            <!--Zobrazení koncertů-->
            <ListView x:Name="seznam"
                      ItemsSource="{Binding}"
                      Grid.ColumnSpan="2"
                      Grid.Column="0"
                      Grid.Row="1"
                      ItemSelected="seznam_ItemSelected">

                <ListView.ItemTemplate>

                    <DataTemplate>

                        <ViewCell>

                            <Grid>

                                <Grid.ColumnDefinitions>

                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>

                                </Grid.ColumnDefinitions>

                                <Label Text="{Binding Termin}" Grid.Column="0"/>
                                <Label Text="{Binding nazev}" Grid.Column="1"/>
                                <Label Text="{Binding misto}" Grid.Column="2"/>
                                <Label Text="{Binding Listky}" Grid.Column="3"/>

                            </Grid>

                        </ViewCell>

                    </DataTemplate>

                </ListView.ItemTemplate>

            </ListView>

            <Label Text="" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="2"/>
            <Label Text="Zadat nový koncert: " FontSize="Medium" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="3"/>
            <Label Text="" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="4"/>


            <!--Účinkující-->
            <Label Text="Účinkující"
                   Grid.Column="0"
                   Grid.Row="5"/>

            <Entry x:Name="eNazev"
                Grid.Column="1"
                Grid.Row="5"/>

            
            
            <!--Místo-->
            <Label Text="Místo"
                   Grid.Column="0"
                   Grid.Row="6"/>

            <Entry x:Name="eMisto"
                Grid.Column="1"
                Grid.Row="6"/>

            
            
            <!--Termín-->
            <Label Text="Termín koncertu"
                   Grid.Column="0"
                   Grid.Row="7"/>

            <DatePicker x:Name="eTermin"
                Grid.Column="1"
                Grid.Row="7"
                Format="dd-MM-yyyy"/>


            
            <!--Lístky-->
            <Label Text="Koupené lístky?"
                   Grid.Column="0"
                   Grid.Row="8"/>

            <Picker x:Name="eListky"
                Grid.Column="1"
                Grid.Row="8">

                <Picker.ItemsSource>

                    <x:Array Type="{x:Type x:String}">
                        <x:String>ano</x:String>
                        <x:String>ne</x:String>
                        
                    </x:Array>

                </Picker.ItemsSource>

            </Picker>

            <Label Text="" Grid.ColumnSpan="2" Grid.Column="0" Grid.Row="9"/>
            
            
            <!--Vložení koncertu-->
            <Button Text="Vložit"
                   Grid.Row="10"
                   Grid.Column="0"
                   Grid.ColumnSpan="2"
                   Clicked="Vlozeni"
                   />

            <!--Upravení koncertu-->
            <Button Text="Upravit"
                    Grid.Row="11"
                    Grid.Column="0"
                    Grid.ColumnSpan="2"
                    Clicked="Upraveni"/>

            <!--Odstranění koncertu-->
            <Button Text="Odstranit"
                    Grid.Row="12"
                    Grid.Column="0"
                    Grid.ColumnSpan="2"
                    Clicked="Odstraneni"/>

        </Grid>

    </ScrollView>


</ContentPage>


XAML.CS:
namespace PMA;

class koncert
{
    public string nazev { get; set; }
    public string misto { get; set; }
    private DateTime? termin;
    private byte listky;

    public koncert(string n, string m, DateTime? t, byte r)
    {
        nazev = n;
        misto = m;
        termin = t;
        listky = r;
    }

    public string Listky
    {
        get
        {
            switch (listky)
            {
                case 0:
                    return "lístky koupené";
                case 1:
                    return "lístky nekoupené";
                default: return "";
            }
        }
    }

    public string Termin
    {
        get
        {
            if (termin == null)
            {
                return "";
            }
            else
            {
                return ((DateTime)termin).ToString("dd.MM.yyyy");
            }

        }
    }

    public DateTime dtTermin
    {
        get { return (DateTime)termin; }
        set { termin = value; }
    }

    public int iListky
    {
        get => listky;
        set { listky = (byte)value; }
    }
}

public partial class MainPage : ContentPage
{
    List<koncert> koncerty = new List<koncert>();

    public MainPage()
    {
        InitializeComponent();
        koncerty.Add(new koncert("Horkýže Slíže","Liberec", new DateTime(2023, 03, 24), 1));
        koncerty.Add(new koncert("Dymytry","Bezděz", new DateTime(2023, 09, 01), 0));
        koncerty.Add(new koncert("Kabát","Bezděz", new DateTime(2023, 09, 02), 0));

        seznam.BindingContext = koncerty;

    }


    private void Vlozeni(object sender, EventArgs e)
    {
        koncerty.Add(new koncert(eNazev.Text, eMisto.Text ,eTermin.Date, (byte)eListky.SelectedIndex));
        seznam.BindingContext = null;
        seznam.BindingContext = koncerty;

        
    }

    private void Upraveni(object sender, EventArgs e)
    {
        koncerty[vybrano].nazev = eNazev.Text;
        koncerty[vybrano].misto = eMisto.Text;
        koncerty[vybrano].dtTermin = eTermin.Date;
        koncerty[vybrano].iListky = eListky.SelectedIndex;
        refresh = true;
        seznam.BindingContext = null;
        seznam.BindingContext = koncerty;
        refresh = false;
    }

    int vybrano;
    bool refresh = false;

    private void seznam_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        if (!refresh)
        {
            vybrano = e.SelectedItemIndex;
            eNazev.Text = koncerty[vybrano].nazev;
            eMisto.Text = koncerty[vybrano].misto;
            eTermin.Date = koncerty[vybrano].dtTermin;
            eListky.SelectedIndex = koncerty[vybrano].iListky;
        }


    }

    private void Odstraneni(object sender, EventArgs e)
    {

        koncerty[vybrano].nazev = eNazev.Text;
        koncerty[vybrano].misto = eMisto.Text;
        koncerty[vybrano].dtTermin = eTermin.Date;
        koncerty[vybrano].iListky = eListky.SelectedIndex;
        koncerty.Remove(koncerty[vybrano]);
        smazat = true;
        seznam.BindingContext = null;
        seznam.BindingContext = koncerty;
        smazat = false;
    }

    bool smazat = false;


}
 
Last edited:
I need help with one problem.
"Zobrazení koupených lístků" and "Zobrazení nekoupených lístků" buttons.

The left button, when pressed, should show a list with only items that have "lístky koupené" written in the list, and the right button, when pressed, should show a list with only items that have "lístky nekoupené" written in the list

XAML:
<!--Filtrace koupených lístků-->
            <Button Text="Zobrazení koupených lístků"
                    Grid.Row="13"
                    Grid.Column="0"
                    Grid.ColumnSpan="1"
                    Clicked="KoupeneFiltr"/>
           

            <!--Filtrace koupených lístků-->
            <Button Text="Zobrazení nekoupených lístků"
                    Grid.Row="13"
                    Grid.Column="2"
                    Grid.ColumnSpan="1"
                    Clicked="NekoupeneFiltr"/>

XAML.CS:
public void KoupeneFiltr(object sender, EventArgs e)
    {
      
    }

private void NekoupeneFiltr(object sender, EventArgs e)
    {
        
    }
 
I need to use StreamWriter and StreamReader.
Why? Is this a school assignment requirement? Or a unit testing requirement?
 
Recall that JSON and XML files are text files too. The simplest thing to do is to serialize your koncerty to/from JSON or XML.
 
Okay. Whatever floats your boat.

In the link below is how to save to a JSON file using either the File.WriteAllText() or a StreamWriter.

 
As an aside, if you look at the source code for File.WriteAllText(), it just ends up using a StreamWriter anyway:

File.WriteAllText():
public static void WriteAllText(String path, String contents, Encoding encoding)
{
    if (path == null)
        throw new ArgumentNullException("path");
    if (encoding == null)
        throw new ArgumentNullException("encoding");
    if (path.Length == 0)
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    Contract.EndContractBlock();

    InternalWriteAllText(path, contents, encoding, true);
}

File.InternalWriteAllText():
private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
{
    Contract.Requires(path != null);
    Contract.Requires(encoding != null);
    Contract.Requires(path.Length > 0);

    using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost))
        sw.Write(contents);
}

 
Ok, thanks. And what about the buttons "Zobrazení koupených lístků" a "Zobrazení nekoupených lístků"? I can't find a way to create it
 
Ok, thanks. And what about the buttons "Zobrazení koupených lístků" a "Zobrazení nekoupených lístků"? I can't find a way to create it
It's because WPF uses RoutedEventArgs, not EventArgs. Perhaps someone is/was trying to modernize an old WinForms tutorial to be WPF and forgot to update their method signatures? It might also explain the need to use text files and the stream writer/reader. A newer tutorial would have opted to using a database.
 
Sorry, I thought you were using WPF. For MAUI, you have it correct, other than usually almost everything in MAUI is async. I don't know if that will make a difference though.

What specific error are you getting trying to hookup the buttons?
 

Latest posts

Back
Top Bottom