Konwersja STRING do INT

0

Witam. Chciałbym prosić o pomoc w zidentyfikowaniu błędu czy o zasugerowanie innego rozwiązania.

2 textBoxy. W jednym znajduje się index. Drugi wyświetla zawartość elementu tablicy[index]

Problem polega na tym, że chciałbym skorzystac z metody TryParse(), ale określić aby uruchamiała się tylko gdy zawartośc textboxa1 nie jest pusta. Stworzyłem taki kod. Drugi poziom if uruchamia się nawet gdy pole jest puste.

int index=1;
private void textBox1_TextChanged(object sender, EventArgs e)
        {
            int index_pom;
            if (textBox1.Text== null)
                if (Int32.TryParse(textBox1.Text, out index_pom))
                {
                    index=index_pom;
                    textBox2.Text = tresc_plik[index];
                }
                else
                {
                    MessageBox.Show("Niepoprawna wartość indexu");
                    textBox1.Text = index.ToString();
                }
        }
 private void textBox2_TextChanged(object sender, EventArgs e)
        {

        } 
1

Przecież ten warunek jest bez sensu. Po co chcesz coś brać z tekstboksu jeżeli jego tekst jest null'em?? O_o

Powinno być raczej if(textBox1.Text != String.Empty) { }.

0

Cześć. Dziękuje na** String.Empty** - rozwiązało to problem. Mógłbyś mi jeszcze objaśnić gdzie popełniłem błąd? Jaka jest różnica w tym przypadku między porównywaniem stringu do null a string.empty. Z góry dziękuje

0

Pierwotnie oczywiście był operator "!=" zamiast "==". Błąd w pierwszym poście, ale chodzi o to że na "!=null" nie działało.

0

Bo w ogóle źle to robisz. Nie rób TryParse bo to jest tutaj bez sensu. Popatrz:

using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Media;
using System.Windows.Forms;


class Program {
    public static void Main(string[] args) {
        var strings = new string[] { "Grzesiek", "Halina" };

        var form = new Form();
        var tb1 = new TextBox();
        var tb2 = new TextBox();

        tb1.TextChanged += (sender, e) => {
            var textbox = sender as TextBox;

            if (!string.IsNullOrWhiteSpace(textbox.Text)) {
                try {
                    var number = Int32.Parse(textbox.Text);
                    if (number < strings.Length) tb2.Text = strings[number];
                    else tb2.Text = "Wrong index";
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.ToString());
                }
            }
            else tb2.Text = string.Empty;
        };

        var layout = new FlowLayoutPanel();
        layout.Controls.Add(tb1);
        layout.Controls.Add(tb2);

        form.Controls.Add(layout);
        form.ShowDialog();
    }
}

A jako, że korzystasz z TextChanged to program nie pozwoli Ci wpisać liczb ujemnych (chociaż na upartego możesz wymusić). Wszystkie nieprawidłowości łapie wyjątek bez robienia out na obiekcie.

Może być też tak:

using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Media;
using System.Windows.Forms;


class Program {
    public static void Main(string[] args) {
        var strings = new string[] { "Grzesiek", "Halina" };

        var form = new Form();
        var tb1 = new TextBox();
        var tb2 = new TextBox();

        tb1.KeyDown += (sender, e) => {
            if (e.KeyData == Keys.Return) {
                var textbox = sender as TextBox;

                if (!string.IsNullOrWhiteSpace(textbox.Text)) {
                    try {
                        var number = Int32.Parse(textbox.Text);
                        if (number >= 0 && number < strings.Length) tb2.Text = strings[number];
                        else tb2.Text = "Wrong index";
                    }
                    catch (FormatException ex) {
                        MessageBox.Show("Parse error: " + ex.ToString());
                    }
                }
                else tb2.Text = string.Empty;
            }
        };

        var layout = new FlowLayoutPanel();
        layout.Controls.Add(tb1);
        layout.Controls.Add(tb2);

        form.Controls.Add(layout);
        form.ShowDialog();
    }
}

Ale wtedy musisz wyłapać także liczby ujemne.

1

@DibbyDum ale napiszę. Czemu by nie :)

using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Media;
using System.Windows.Forms;


class Program {
    public static void Main(string[] args) {
        var strings = new string[] { "Grzesiek", "Halina" };

        var form = new Form();
        var tb1 = new TextBox();
        var tb2 = new TextBox();

        tb1.KeyDown += (sender, e) => {
            if (e.KeyData == Keys.Return) {
                var textbox = sender as TextBox;

                var number = 0;
                if (!string.IsNullOrWhiteSpace(textbox.Text)) {
                    if (Int32.TryParse(textbox.Text, out number)) {
                        if (number >= 0 && number < strings.Length) tb2.Text = strings[number];
                        else tb2.Text = "Wrong index";
                    }
                    else MessageBox.Show("Parse error!");
                }
            }
        };

        var layout = new FlowLayoutPanel();
        layout.Controls.Add(tb1);
        layout.Controls.Add(tb2);

        form.Controls.Add(layout);
        form.ShowDialog();
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1