我有三个按钮。并具有两个带有随机行的列表字符串。我希望能够按两个第一个按钮来更改第三个按钮上的“操作”。如果单击第一个按钮,则第三个按钮仅使用“ HEB”,如果单击第二个按钮,则第三个按钮使用“ HEC”
按下button1时,我希望button3这样做:
HEB f1 = new HEB();
textBox1.Text = f1.RandomString();
按下button2时,我希望button3这样做:
HEC f2 = new HEC();
textBox1.Text = f2.RandomString();
解决此问题的最佳方法是什么?
编辑: HEB和HEC是单击button3时显示在文本框1中的随机文本。
完整代码:
namespace Questions
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
HEB f1 = new HEB();
textBox1.Text = f1.RandomString();
}
private void button2_Click(object sender, EventArgs e)
{
HEC f2 = new HEC();
textBox1.Text = f2.RandomString();
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}
public class HEB
{
List<string> list = new List<string>
{
"This is test number 1",
"This is test number 2",
"This is test number 3"
};
public string RandomString()
{
Random r = new Random();
int index = r.Next(list.Count);
string randomString = list[index];
return randomString;
}
}
public class HEC
{
List<string> list = new List<string>
{
"This will show later number 4",
"This will show later number 5",
"This will show later number 6",
};
public string RandomString()
{
Random r = new Random();
int index = r.Next(list.Count);
string randomString = list[index];
return randomString;
}
}
答案 0 :(得分:0)
您可能有一个包含当前“消息”的列表,可以使用前两个按钮将其更改为预定义的值,然后在按下第三个按钮时从当前消息中随机选择一个。
类似的东西:
public partial class Form1 : Form
{
private List<string> messages;
private string RandomString()
{
Random random = new Random();
return messages[random.Next(messages.Count)];
}
//To use it just do:
//(if it is a button it should have a method that it triggers on use)
private void HEB()
{
//same for HEC, but other strings (test 3 and 4)
messages = new List<string>(){"test 1", "test 2"};
}
private void TheButton()
{
textBox1.text = RandomString();
}
}
这应该可以,但是不要害怕要求更多的澄清:)
编辑:更新的代码有效(只需添加变量,然后用我内部的代码替换当前按钮内的代码)即可。
namespace Test_btns
{
public partial class Form1 : Form
{
private List<string> messages;
Random random = new Random();
private string RandomString()
{
return messages[random.Next(messages.Count)];
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
messages = new List<string>() { "test 1", "test 2" };
}
private void button2_Click(object sender, EventArgs e)
{
messages = new List<string>() { "test 3", "test 4" };
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = RandomString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//not really needed for this, but the method exists.
}
}
}