Good afternoon, tell me how you can set the number of elements of an array of TextBox?

You should get something like:

string[] myArr = new string[TextBox.Text]; 

It gives an error that can not convert string to int

Or maybe tell me another way, I need to based on the number entered in the TextBox to add entries to the ListBox.

    3 answers 3

    Right! Text is a string . Make int32.Parse(TextBox.Text) and you will be happy.

    • For good, first you need to check user input, so it’s better to use TryParse - Bulson
    • @Bulson, yes, but it is possible that his TextBox has a limit on entering characters and this check will be unnecessary. - iluxa1810
    • 2
      The one who asked such a question ... there will be a restriction ... don't make me laugh. - Bulson

    Text property of the TextBox element. Gets or sets the text content of the text field ( string ).

    To create an array of a given length, you must use the following construction:

     type[] array = new type[N]; 

    Where

    • type - the type of variables contained in the array. The array elements can be of any type, including the type of the array;
    • N is the number of elements in the array. Must be represented by a positive integer, including 0. The table of integer types can be viewed on the MSDN website

    In this particular case, you pass the type string .

    string [] myArr = new string [TextBox.Text];

    To solve the problem, you must cast the contents of TextBox.Text to an integer type. I will give an example of conversion. This example takes into account that the correct data is entered in TextBox.Text .

     n = int.Parse(TextBox.Text); 

      An alternative way to use MVVM is to bind the TextBox to an integer property.

       class VM : INotifyPropertyChanged { int n; public int N { get { return n; } set { if (n != value) { n = value; NotifyPropertyChanged(); } } } // ... void OnUserAction { string[] myArr = new string[N]; // ... } } 

      Accordingly, in the XAML bind:

       <TextBox Text="{Binding N}" ... /> 

      (Of course, there are still needed checks, without them nowhere.)