1

I'm doing a windows form app and I need to declare empty array for some listbox operations. But i can't add value to array. When I try to print the lenght of the array after adding a value I reading the value 0 all the time.

public partial class Form1 : Form
    {
        public static int[] arrayOfNumbers = new int[] { };
        public Form1()
        {
            InitializeComponent();
        }
        
        public void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(textBox1.Text);
           
            arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text));
            Console.WriteLine(arrayOfNumbers.Length);
            
        }
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 4
    When you find yourself adding and removing values from an array, using a [list](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0) may be the better choice. – devsmn Oct 18 '21 at 11:35
  • 1
    I've removed the windows-forms-designer tag as there's nothing Forms-specific about this question... and definitely nothing specific to the *designer*. I strongly recommend that when providing an example, you try to do so in a console app... that tends to lead to simpler examples, and isolates the problem from any particular UI technology. – Jon Skeet Oct 18 '21 at 11:35
  • Does this answer your question? [Adding values to a C# array](https://stackoverflow.com/questions/202813/adding-values-to-a-c-sharp-array) – Filburt Oct 18 '21 at 11:43

3 Answers3

4

Enumerable.Append appends an item to a sequence and returns it, so you need to use it to re-assign a new array to the field. But it doesn't return an arrray but IEnumerable<T>, so you have to append ToArray:

arrayOfNumbers = arrayOfNumbers.Append(Convert.ToInt32(textBox1.Text)).ToArray();

Arrays are a fixed size collection which you can't modify anyway.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • There is any option at NET 6 to avoid Lists? The performance of this is really really bad – Leandro Bardelli Mar 07 '23 at 03:30
  • 1
    @LeandroBardelli: I'm sure it's bad perfromance is not caused by `ToList` or `ToArray` but because of the query that you use. So maybe you want to ask a question where you give us all relevant information. – Tim Schmelter Mar 07 '23 at 08:53
1

Besides Tim Schmelter's answer being absolutely correct, what the OP most apparently wanted to do is using a List<int> and its Add method instead of an array1.

Append is a so called LINQ method, which would return a "copy"2 of the array with that value appended, not modifying the instance you called it on, which is not what was intended to happen.

public partial class Form1 : Form
{
    public static List<int> arrayOfNumbers = new(); // use a List<int>

    public Form1()
    {
        InitializeComponent();
    }
    
    public void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add(textBox1.Text);
        
        arrayOfNumbers.Add(Convert.ToInt32(textBox1.Text)); // extend instance with Add
        Console.WriteLine(arrayOfNumbers.Count); // use List's Count property
    }

1 I suppose the OP has a Python background, since Python "lists" look like C# arrays due to the square brackets, and do not have a fixed size. The C# companion to Python lists are List instances, however, with slightly different method names like Add instead of Append.

2 This statement is extremely simplified since LINQ is lazy-evaluated, only returning an enumerator with the effects you want it to have once you iterated through it, never modifying the instance you call it on or creating new instances by itself.

Ray
  • 7,940
  • 7
  • 58
  • 90
0
public void Submit_Click(object sender, RoutedEventArgs e)
    {
        ListUser[] Acts = {};     //Empty string array
        int length = Acts.Length; //get array length to int
        int ActInt = length;      //assign to separate int var


                                  //--if--//
                                  //Check if array is 0 length and append
                                  //values from two textboxes to the Acts 
                                  //array.
                                  //Get new length of Acts array and assign 
                                  //to int length and int ActInt.
                                  //Then create an array to hold a copy of 
                                  // the values using correct length
                                  //Bind Acts array to ListView DataSource
                                  //--else--//
                                  //If Acts array is not empty "0" write 
                                  //vals to console. AKA Append again.
         if (ActInt==0)
           {
               Acts = Acts.Append(new ListUser(NameEntry.Text, TimeEntry.Text)).ToArray();
               length = Acts.Length;
               ActInt = length;                   
               ListUser[] ActsOld = new ListUser[ActInt];
               System.Array.Copy(Acts, ActsOld, ActInt);
               ActsList.ItemsSource=Acts;
           }
        else if (Acts!=0)
           {
               /*Append to array here and remove foreach*/
               //--|--//
               //--V--//
               foreach (var i in Acts)
               {
                   Console.WriteLine(i);
               }
           }
    }

Where ListUser[] Is A Second Class File To Define The Attributes Of The Array

public class ListUser
    {
        public string lName { get; set; }
        public string lTime { get; set; }

        public ListUser(string lname, string ltime)
        {
            lName = lname;
            lTime = ltime;
        }

    }

Thank You for Your Help Tim your answer utilizing;

arr = arr.Append(element(params)).ToArray();

Worked perfectly.

If anybody could advise on a quick and dirty way to click and drag to reorder entries within a ListView / GridView any help would be great!!

<ListView x:Name="ActsList">
                <ListView.View>
                    <GridView x:Name="ActsListGrid">
                        <GridView.Columns>
                            <GridViewColumn Width="300"
                                            Header="Name"
                                            DisplayMemberBinding="{Binding lName}" />
                            <GridViewColumn Width="80"
                                            Header="time"
                                            DisplayMemberBinding="{Binding lTime}" />

                        </GridView.Columns>
                    </GridView>
                </ListView.View>
            </ListView>
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/31676526) – dorphalsig May 07 '22 at 14:57