永发信息网

C# 代码简化问题

答案:3  悬赏:0  手机版
解决时间 2021-06-02 01:06
  • 提问者网友:皆是孤独
  • 2021-06-01 07:17

private void p_button1_Click(object sender, EventArgs e)
{
position = richtext.SelectionStart;
richtext.Text = richtext.Text.Insert(position, p_button1.Text);
richtext.Focus();
richtext.SelectionStart = position + p_button1.Text.Length;
}

private void p_button2_Click(object sender, EventArgs e)
{
position = richtext.SelectionStart;
richtext.Text = richtext.Text.Insert(position, p_button2.Text);
richtext.Focus();
richtext.SelectionStart = position + p_button2.Text.Length;
}

private void p_button3_Click(object sender, EventArgs e)
{
position = richtext.SelectionStart;
richtext.Text = richtext.Text.Insert(position, p_button3.Text);
richtext.Focus();
richtext.SelectionStart = position + p_button3.Text.Length;
}

这三段代码除了p_button后的数字不同外,其他都相同,请问有没办法使它简化,我有好几十个按钮,总不可能每个都写吧、、、、

最佳答案
  • 五星知识达人网友:想偏头吻你
  • 2021-06-01 08:35
专门写个函数来实现单击按钮内部的操作可以不
全部回答
  • 1楼网友:逃夭
  • 2021-06-01 09:47
所有的button都把click事件关联到同一个事件处理方法里,然后用(sender as button)来引用各个对象,这是个小例子,你运行一下应该就知道该怎么做了: using System; using System.Windows.Forms; class Test { static void Main() { Form f = new Form(); Button b1 = new Button(); Button b2 = new Button(); f.Controls.Add(b1); f.Controls.Add(b2); b1.Text = "1"; b2.Text = "2"; b2.Location = new System.Drawing.Point(0, b1.Height); b1.Click += new EventHandler(click); b2.Click += new EventHandler(click); Application.Run(f); } static void click(object sender, EventArgs e) { Console.WriteLine((sender as Button).Text); } }
  • 2楼网友:空山清雨
  • 2021-06-01 08:47

private void p_button3_Click(object sender, EventArgs e) { position = richtext.SelectionStart; richtext.Text = richtext.Text.Insert(position, (Button)Sender.Text); richtext.Focus(); richtext.SelectionStart = position + (Button)Sender.Text.Text.Length; }

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯