C# 使用变量设置标签文本
我正在为学校做一项作业,我需要读取用户名(并生成考试分数),我想在用户从Windows窗体点击“提交考试”按钮时,使用标签将此信息显示回用户。我试过几种不同的方法C# 使用变量设置标签文本,c#,C#,我正在为学校做一项作业,我需要读取用户名(并生成考试分数),我想在用户从Windows窗体点击“提交考试”按钮时,使用标签将此信息显示回用户。我试过几种不同的方法 label3.Text=“{0}{1}”,姓名,分数失败 我也尝试过: label3.Text=test.ToString()已起作用,但GUI显示System.Windows.Forms.TextBox,Text:(名称)(分数) 这是我正在使用的代码片段,如果我需要发布更多,请告诉我 private void btnSubmitT
label3.Text=“{0}{1}”,姓名,分数代码>失败
我也尝试过:
label3.Text=test.ToString()代码>已起作用,但GUI显示System.Windows.Forms.TextBox,Text:(名称)(分数)
这是我正在使用的代码片段,如果我需要发布更多,请告诉我
private void btnSubmitTest_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
string name = txtName.ToString();
//Generate a new test that passes in
Test tests = new Test(name, score);
label3.Text = tests.ToString();
}
我对C#很陌生,所以如果有任何额外有用的信息,我会洗耳恭听。你几乎做到了
label3.Text = String.Format ("{0} {1}", name, score);
如果要获取或设置文本框的文本
,请使用其文本
属性。
在新对象上调用ToString()
不会得到预期的结果,除非您重写了ToString()
方法
像这样试试
private void btnSubmitTest_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
label3.Text = String.Format("{0} {1}", name, score);
}
Test test1=new Test("Hello All",1);
string TextObject = test1.ToString();
这很简单
你有很多方法来解决它
String.Format("bla {0} blabla {1}",var1,var2);
或
正如您所见,这种方法比使用+运算符连接字符串要好
最有效的方法之一是重写类中的ToString()
方法
class Test
{
private string _a;
private int _b;
public Test(string a, int b)
{
_a = a;
_b = b;
}
public override string ToString()
{
return string.Format("{0}, {1}", _a, _b);
}
}
这允许您以非常可转售的方式打印出您的对象
就这样
private void btnSubmitTest_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
label3.Text = String.Format("{0} {1}", name, score);
}
Test test1=new Test("Hello All",1);
string TextObject = test1.ToString();
这是推荐的关闭方式,但实际上您需要的是Textbox
对象的Text
属性。请尝试以下操作:string name=txtName.Text
。就像您在最后一行中分配标签3
的Text属性一样。测试
课程是你创造的,还是教授提供的?因为您可能也会得到一些您不期望的结果。我不确定Test(name,score)
返回什么,但您可以尝试label3.Text=tests.name
而不是label3.Text=tests.ToString()代码>您的测试对象看起来像什么?您可能需要访问属性,并将它们作为连接指定给标签。ToString()不会提供对象的字符串表示形式。所以label3.text=tests.PropertyName+tests.PropertyName2Or$@“{name}{score}”和C#6