更改文本框时的C#自动更新图表

时间:2014-10-24 22:10:05

标签: c# r winforms events event-handling

我有一个由一系列文本框和一个按钮组成的窗体。 用户需要将一些数据输入到文本框中,然后代码使用这些输入进行一些计算。 然后,用户单击该按钮,将生成一个显示计算结果的图表。 图表是使用R完成的,R通过R.Net连接到C#。

问题是:如果用户更改其中一个文本框中的某些输入,我怎样才能使图表动态更新(所以不先点击生成图形的按钮)?

我认为我需要一些循环来不断检查是否有任何文本框已被更改但我无法使其工作:

foreach (Control subctrl in this.Controls)
    {
        if (subctrl is TextBox)
        {
            ((TextBox)subctrl).TextChanged += new EventHandler();
        }

    }

TextChanged应该触发buttonClick事件,以便执行生成图表的reated代码。 这个问题的好方法是什么?感谢。

<<<<编辑>>>>>

以下是表单的代码:

public partial class myInputForm : Form
{
    public myInputForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) 
    {
       // call methods to run calculations using new inputs from textboxes
       plotGraph(); // plot the new results
    }

}

我想在button1_Click事件中保留计算方法和绘图函数 plotGraph()

尝试采用Refus L'的建议,我将以下内容添加到上面的部分类myInputForm中:

private void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox textbox = sender as TextBox;
    if (IsValidText(textBox.Text)) 
    {
         textbox.TextChanged += new System.EventHandler(this.button1_Click);
    }
    else
    {
    DisplayBadTextWarning(textBox.Text);
    }
}


private void myInputForm_Load(object sender, EventArgs e)
{
    foreach (Control control in this.Controls)
    {
        var textBox = control as TextBox;
        if (textBox != null)
        {
            textBox.TextChanged += TextBox_TextChanged;
        }
    }
 } 

但这仍然无效。如果我插入以下内容:

this.myFirstBox.textChanged += new System.EventHandler(this.button1_Click);

直接在其工作的表单设计器自动生成的代码中,文本框中的更改myFirstBox触发按钮单击,从而触发绘图。 但我需要为每个文本框写一行,因为foreach在那里不起作用。 你能解释一下如何设置它以我的形式工作吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您只需指定要处理事件的现有方法即可。理想情况下,您有一个更新图表的单独方法,可以从任何地方调用。然后你可以从TextChanged或Button_Click事件中调用它,但这两个控件事件没有绑在一起(在TextChanged中你可能想先对文本进行一些验证)。此外,如果您想要从其他地方更新图表,您可以使用一种独立的方法来执行此操作。

例如,如果您有此方法来更新图表:

private void UpdateChart()
{
    // Do something here to update the chart
}

您可以从事件处理程序中调用它:

private void button1_Click(object sender, EventArgs e)
{
    UpdateChart();
}

private void TextBox_TextChanged(object sender, EventArgs e)
{
    // You might have some data validation on the TextBox.Text here, 
    // which you wouldn't need in the Button_Click event
    TextBox textbox = sender as TextBox;
    if (IsValidText(textBox.Text)) 
    {
        // Now update the chart
        UpdateChart();
    }
    else
    {
        DisplayBadTextWarning(textBox.Text);
    }
}

然后,您可以将所有TextBox.TextChanged事件连接到上面的自定义处理程序:

private void Form1_Load(object sender, EventArgs e)
{
    // Dynamically hook up all the TextBox TextChanged events to your custom method
    foreach (Control control in this.Controls)
    {
        var textBox = control as TextBox;
        if (textBox != null)
        {
            textBox.TextChanged += TextBox_TextChanged;
        }
    }
}