Home > Enterprise >  line's value is null while in a method
line's value is null while in a method

Time:11-05

Alright, so I made a terribly optimized piece of code that should check the application's current path, list all the .wav files and then have a button that allows me to add the file's full path but problem is, when I try to do Trace.WriteLine(line) it works fine and lists the file names but inside the "addtoNuts" it just sees it as empty and only adds the current directory to the list. I tried just tracing the line but it still just gives me nothing. Code :

List<string> nuts = new List<string>();

public fileSelector()
{
    InitializeComponent();
    if (Directory.Exists(Directory.GetCurrentDirectory()   "/videos/"))
    {
        string files = String.Join(Environment.NewLine, Directory.GetFiles($"{Directory.GetCurrentDirectory()}/videos/", "*.wav"));
        string files3 = files.Replace($"{Directory.GetCurrentDirectory()}/videos/", "");
        var i = 0;
        using (var reader = new StringReader(files3))
        {
            for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
            {
                Trace.WriteLine(line);

                TextBlock name = new TextBlock()
                {
                    Text = line.Replace("_", " ").Replace(".wav", ""),
                    FontSize = 20,
                    Width = 500,
                    HorizontalAlignment = HorizontalAlignment.Left,
                    Foreground = Brushes.White
                };

                fileList.Children.Add(name);

                Button add = new Button() {
                    Height = 45,
                    Width = 45,
                    Content = new Image
                    {
                        Source = new BitmapImage(new Uri($"{Directory.GetCurrentDirectory()}/Images/newPlaylist.png")),
                        VerticalAlignment = VerticalAlignment.Center
                    }
                };
                
                void addtoNuts(object sender, RoutedEventArgs e)
                {
                    nuts.Add($"{Directory.GetCurrentDirectory().Replace("\\","/")}/{line}");
                    Trace.WriteLine(string.Join("\t", nuts));
                    //Trace.WriteLine(line);
                }

                add.Click  = addtoNuts;
                
                i  ;

                fileList.Children.Add(add);
            }

        }
    }
}

CodePudding user response:

What should you change to get this working

 Button add = new Button() {
    Height = 45,
    Width = 45,
    Content = new Image
    
    Source = new BitmapImage(new Uri($"Directory.GetCurrentDirectory()}/Images/newPlaylist.png")),
    VerticalAlignment = VerticalAlignment.Center,

    Tag = line //<- This line here
}

And then in your addToNuts function replace line with Button.Tag

void addtoNuts(object sender, RoutedEventArgs e)
{
      var btn = sender as Button;
      nuts.Add($"{Directory.GetCurrentDirectory().Replace("\\","/")}/{btn?.Tag}");
                        Trace.WriteLine(string.Join("\t", nuts));
                        //Trace.WriteLine(line);
}

Why was it not working

When your for loop executes it creates numerous buttons and labels. And for each button it creates a click event which points to addToNuts.

At the end of for loop value of line is null.

Now when you click on any Button in your list it executes addToNuts function and try to get value of variable line which is null as the loop has already finished.

What we changed

Now I assigned value of line inside the for loop to Tag property of Button.

Tag: Gets or sets an arbitrary object value that can be used to store custom information about this element.

This stored value of line inside the button, so when you click on the button it gets the clicked button from sender and use its Tag value.

Free Advice :)

You do not need StringReader to iterate over files, you can replace below code -

string files = String.Join(Environment.NewLine, Directory.GetFiles($"{Directory.GetCurrentDirectory()}/videos/", "*.wav"));
            string files3 = files.Replace($"{Directory.GetCurrentDirectory()}/videos/", "");
            var i = 0;
            using (var reader = new StringReader(files3))
            {
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                {

With -

var files = System.IO.Directory.GetFiles($"{System.IO.Directory.GetCurrentDirectory()}/videos/", "*.wav");
        foreach (var file in files)
        {
            var line = System.IO.Path.GetFileName(file);

You can experiment more with System.IO.Path() to get desired result.

  • Related