C# 如何使用button按钮的Click事件修改label的Text值

qq_25855569 2018-07-26 01:00:08
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mynamespace
{
class DLabel2
{
public void DrawLabel(int Number, UserControl e)
{
for (int i = 1; i < Number; i++)
{
//文档
Label lb = new Label();
lb.Name = "Label" + i;
lb.Text = "Label" + i;
lb.TextAlign = ContentAlignment.MiddleCenter;
lb.Size = new Size(100, 100);
lb.ForeColor = System.Drawing.Color.White;
lb.Font = new Font("宋体", 26);
lb.Location = new System.Drawing.Point(10 + 10 * i, 10 + 10 * i);
e.Controls.Add(lb);


//按钮
Button btn = new Button();
btn.Name = "Button" + i;
btn.Text = "Button" + i;

btn.BackColor = System.Drawing.Color.White;

btn.Font = new Font("宋体", 26);
btn.Click += new EventHandler(btn_Click);
btn.Size = new Size(100, 100);
btn.Location = new Point(100 + 10 * i, 100 + 10 * i);
e.Controls.Add(btn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
MessageBox.Show(btn.Name);

}
}
}



自定义了一个方法,根据输入的个数,自动创建等数量的Label和Button。现在想用Button1的Click事件来改变Label1的Text值,同理Button2控制Label2…等。请问有什么方法可以实现?
...全文
2211 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
你可以定义一个
private List<Label> Container = new List<Label>();
集合来记录那些控件。

用什么 Find?
壶中日月长 2018-07-26
  • 打赏
  • 举报
回复
在创建button的时候把Lable赋值给button.Tag:

Button btn = new Button();
btn.Tag = lb;


在btn_Click中把lable拿出来:

Button btn = sender as Button;
Label lb = btn.Tag as Label;
lb.Text = "xxx";
xuzuning 2018-07-26
  • 打赏
  • 举报
回复
string labelName = (sender as Button).Name.Replace("Button", "Label");
Controls[labelName].Text = ".....";
游北亮 2018-07-26
  • 打赏
  • 举报
回复
哦哦,上面代码写错了:
public void btn_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    // 根据按钮名,匹配出Label的名
    string labelName = "Label" + btn.Name.Replace("Button", "");
    // 查找控件
    Label label = (Label) (btn.Parent.Controls.Find(labelName, true)[0]);
    label.Text = "xxxxx";
}
qq_25855569 2018-07-26
  • 打赏
  • 举报
回复
我也试过用controls.find 这个方法来找。结果controls在报错。
游北亮 2018-07-26
  • 打赏
  • 举报
回复

public void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
// 根据按钮名,匹配出Label的名
string labelName = "Label" + btn.Name.Replace("Button", "");
// 查找控件
Label label = (Label) (aa.Controls.Find(labelName, true)[0]);
label.Text = "xxxxx";
}
jun471537173 2018-07-26
  • 打赏
  • 举报
回复
可以通过Controls查找到对应的Label吗

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧