单击按钮时文本未显示在标签中

时间:2013-09-01 19:54:42

标签: c# visual-studio-2010

我正在处理我正在处理的项目,包括单击按钮,文本应该显示在我创建的标签框中。我知道当我点击按钮时,使用文本框显示文本会更容易,但我的教师希望我们使用标签来显示文本。我调试了项目,一切都说很好,但当我点击底部的一个按钮时,文本不会显示在指定的标签中。以下是我正在使用的代码。也许我错过了什么。例如,当我点击客户关系按钮时,它应该在一个标签中显示部门,在下一个标签中显示联系人姓名,在下一个标签中显示电话号码。我希望这是足够的信息

private void btnCustomerRelations_Click(object sender, EventArgs e)
{
    lblDepartment.Text = "Customer Relations";
    lblContact.Text = "Tricia Smith";    
    lblPhone.Text = "500-1111";
}

private void btnMarketing_Click(object sender, EventArgs e)
{
    lblDepartment.Text = "Marketing";    
    lblContact.Text = "Michelle Tyler";    
    lblPhone.Text = "500-2222";    
}

private void btnOrderProcessing_Click(object sender, EventArgs e)    
{    
    lblDepartment.Text = "Order Processing";    
    lblContact.Text = "Kenna Ross";    
    lblPhone.Text = "500-3333";   
}

private void btnShipping_Click(object sender, EventArgs e)    
{    
    lblDepartment.Text = "Shipping";    
    lblContact.Text = "Eric Johnson";    
    lblPhone.Text = "500-4444";    
}

2 个答案:

答案 0 :(得分:2)

Did the project compiled without any errors ?

默认情况下,C#中的每个事件处理程序都声明为void,我无法在您的代码中找到它。您修改Visual Studio生成的事件处理程序,如果是这种情况,那么您面临的问题是因为此

让我解释会出现什么问题;

每当使用Visual Studio的“属性”窗口为任何控件创建事件处理程序时,为了便于解释,我可以使用example of TextBox。假设您有一个TextBox(名为textBox1,这是默认值)和您订阅了它的TextChanged Event(为了在Visual Studio的事件窗口中找到TextChanged事件并双击它,当您这样做时,Visual Studio会为您生成;

private void textBox1_TextChanged(object sender,EventArgs e)
{

}

这是我们程序员称之为Event Handler的内容,现在找到Solution Explorer Window in Visual Studio点击Form1.Designer.cs您会在那里获得大量代码,找到说明的行

private System.Windows.Forms.TextBox textBox1;

其中textBox1是控件的名称。在此点上方找一个加号,单击它并找到以下代码;

// 
// textBox1
// 
this.textBox1.AcceptsReturn = true;
this.textBox1.Location = new System.Drawing.Point(478, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(359, 23);
this.textBox1.TabIndex = 1;
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

PS:The Location , AcceptsReturn , Size and TabIndex property in yours might not be same as mine.

阅读此代码的最后一行,它说;

this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);

其中textBox1_TextChanged is the name of event which must be same as that defined in Form1.cs.如果你修改它,你会得到各种编译时错误。

所以现在我想你知道Form1.cs(主代码文件)和Form1.Designer.cs(代码隐藏文件)之间的关系是什么。

在一行中,结论是确保;

Any event handler function in Form1.cs private void .... 开头,而private void之后的单词与该特定控件的代码隐藏文件中定义的完全相同。如果您愿意阅读有关此内容的更多信息,请查看here

希望它能帮助你解决这个问题。还有别的东西请告诉我。

答案 1 :(得分:0)

您是否尝试在每种方法的末尾插入Application.DoEvents()语句?有时表单很难更新标签,而且该方法会强制表单重绘自己。