我正在使用此代码创建带有两行文字的按钮
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
int n = 0;
int s = 99;
for (int i = 0; i < 20; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
panel1.Controls.Add(button); // here
button.Size = new Size(50, 50);
if (i == 4 || i == 9||i==14||i==19)
{
top = 30;
left = 23;
top +=button.Top+2;
left += button.Width+2;
}
else
left += button.Width + 2;
n = n + 1;
s = s + 1;
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Click += Button_Click;
}
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(s);
}
所以当我点击动态按钮时,我只需要选择第二行我的按钮文本。我该怎么做?
答案 0 :(得分:0)
您可以在Tag
属性中存储一些数据:
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Tag = new int[] { n, s };
以后再回过头来使用:
private void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
var data = button.Tag as int[];
string s = data[1].ToString();
MessageBox.Show(s);
}
答案 1 :(得分:0)
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(button.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1]);
}