简体   繁体   中英

Help using TextBox and RichTextBox

I'm making a menu type of all kinds of sorting algorithm. the user will input ten numbers in the TextBox, select a RadioButton, then click the generate button. the output must show each line on how the algorithm works.

(Selection Sort)

sample input from TextBox: 9 6 8 7 5 2 3 1 10 4

output:

1 6 8 7 5 2 3 9 10 4 \n
1 2 8 7 5 6 3 9 10 4 \n
1 2 3 7 5 6 8 9 10 4 \n
1 2 3 4 5 6 8 9 10 7 \n
1 2 3 4 5 6 7 9 10 8 \n
1 2 3 4 5 6 7 8 10 9 \n
1 2 3 4 5 6 7 8 9 10 \n

I made a program like these on Java, but I only used JOptionPane. I do not have any ideas on how to convert it to c# and by using TextBox and RichTextBox.

Here's my codes so far. My output always show a lot of zeros.

   int[] nums = new int[10]; 
   int i, s, min, temp;

   private void EnterNum_TextChanged(object sender, EventArgs e)
   {
       string[] nums = EnterNum.Text.Split(' '); 
       //int[] nums = new int[] { int.Parse(EnterNum.Text) };
   } 

   private void GenerateButton_Click(object sender, EventArgs e)
   {
       if (SelectionRadio.Checked == true)
       {
           for (i = 0; i < nums.Length - 1; i++)
           {
               min = i; 
               // In each iteration, find the smallest number
               for (s = i + 1; s < nums.Length; s++)
               {
                   if (nums[min] > nums[s])
                   {
                       min = s;
                   }
               }
               if (min != i)
               {
                   temp = nums[i];
                   nums[i] = nums[min];
                   nums[min] = temp;
               }
               Display();
           }
       }
       Display();
   }

   private void ClearButton_Click(object sender, EventArgs e)
   {  
       richTextBox1.Clear();
   }

   public void Display()
   {
       int i;
       String numbers = "";
       for (i = 0; i < 10; i++)
         numbers += Convert.ToInt32(nums[i]).ToString() + " ";
       richTextBox1.AppendText(numbers);
   }

before starting algorithm you need to fill your nums array from textbox, you see zeros because by default array is filled with zeros and you just displaying default array:

string[] numsInString = EnterNum.Text.Split(' ');
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
    nums[j] = int.Parse(numsInString[j]);
}  
if (SelectionRadio.Checked == true)
//...

and to display nicely add "\\n" when appending text:

richTextBox1.AppendText(numbers+"\n");

also as Matt mentioned use .ToString() , your nums are integers already so you dont need to convert int to int :

numbers += nums[i].ToString() + " ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM