0

How can I make int input to string input in C#? How can I change the int input to string input, so the user can write letters to the textbox, instead of numbers? I have tried myself, but the code won't work anymore. I know the solution is easy, but can't figure it out..

Here is my code:

public partial class MainWindow : Window
{
    int[] arvat = new int[10];
    int i = 0;
    int k = 0;

    public MainWindow()
    {
        InitializeComponent();
    }
    private void btnNimi_Click(object sender, RoutedEventArgs e)
    {

     int nimet = int.Parse( txtNimi.Text);

        if (i < arvat.Length)
        {
            arvat[i] = nimet;
            i++;
            txtNimi.Text = "";
            txtNimi.Focus();
        }

        else
        {
            MessageBox.Show("Kaikki arvat on syötetty.");
            txtNimi.Text = "";
        }
    }

    private void btnArpa_Click(object sender, RoutedEventArgs e)
    {
        int arpa = 0;
        Random r = new Random();

        arpa= r.Next(0, 9);

        txbArvonta.Text = "";

        for (int i = 0; i < arvat.Length; i++)
        {
            txbTeksti.Text = "\n" + "Kaikki osallistuneet: " + "\n";
            txbArvonta.Text += arvat[i] + "\n";

         int arpominen = arvat [k];

         txbVoittaja.Text = "Ja voittaja on: " + arvat[arpa].ToString() + "\n" + "Onnea voittajalle!";
        }
1
  • Don't do this: int nimet = int.Parse( txtNimi.Text); Commented Apr 16, 2015 at 12:17

1 Answer 1

1

Instead of using Int.Parse, try using Int.TryParse to determine if the input will evaluate to a number before storing the result.

     int number = 0;
     bool isNumeric = Int32.TryParse(arvat[i], out number);
     if (isNumeric)
     {
        Console.WriteLine("'{0}' is a number {1}.", arvat[i], number);         
     }
     else
     {
        Console.WriteLine("'{0}' is text.", arvat[i]);
     }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.