_textChanged事件给我错误“对象引用未设置为对象的实例”

时间:2011-09-08 03:46:48

标签: c# textchanged

我是C#的新手,所以仍然找到我的方法。

我有一个按钮,我想只在用户输入文本到文本框时启用。 我收到此错误 - “对象引用未设置为对象的实例”。

以下是相关代码(没有使用和变量):

    public MainWindow()
    {
        MessageBox.Show("Make sure to edit Settings tab.");
        InitializeComponent();
        if (startTextBox.Text == "0")    // Checks to see if a textbox has some text other than zero. if no than the user cannot press button1 yet.
        {
            button1.IsEnabled = false;
        }
        else
        {
            button1.IsEnabled = true;
        }

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        if (radioButton1.IsChecked == false)
        {
            label17.Content = "No Hourly wage was set.";
        }

    }

    private void add(object sender, RoutedEventArgs e)    /// here is a very long method so I've removed its content.


    }


    public void printTime()
    {

        int Sum = (this.EndInt - this.StartInt);
        int Money = (Sum * this.L1001);


        label16.Content = Sum;
        label17.Content = Money;
        if ((textBox1.Text == "0") && ((textBox2.Text == "0") || (textBox3.Text == "0")))
        {
            label17.Content = "No Hourly wage was set.";
        }
    }

    public void printTime2()
    {

        int Sum = (this.EndInt - this.StartInt);
        MessageBox.Show("Is it possible that you've worked - " + Sum + " Hours?");
    }

    public void printTime3()
    {

        int Sum = (this.EndInt - this.StartInt);
        int Money = (Sum * this.L1001);

        label16.Content = Sum;
        label17.Content = Money;
        if (textBox1.Text == "0")
        {
            label17.Content = "No Hourly wage was set.";
        }
    }


    public int Convert(String S)
    {
        int i = int.Parse(S);
        return i;
    }


    // Input Validation For Excepting Integers Only!
    private void input(object sender, TextCompositionEventArgs e)
    { CheckIsNumeric(e); }
    private void CheckIsNumeric(TextCompositionEventArgs e)
    {
        int result; if (!(int.TryParse(e.Text, out result) || e.Text == "."))
        { e.Handled = true; MessageBox.Show("Numbers Only"); }

    }


    private void startTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {

        button1.IsEnabled = true;
    }




}

}

1 个答案:

答案 0 :(得分:1)

这是范围问题。您没有显示button1的定义位置。但是在你的事件处理程序 startTextBox_TextChanged 中,无法找到button1定义(实际上它也需要实例化)。由于您尝试在尚未实例化的对象(button1)上调用方法,因此抛出了该异常。

如果您发布的不仅仅是那些片段,我或其他人可能会进一步帮助您。