我需要使用一个按钮来制作一些带有相关按钮的文本框,每个按钮会在文本框中添加1(我想与它相关如何?)
==========================================
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace AdvancedCounter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (panel3.Controls != null)
{
var btn = panel3.Controls.Find("_B", true).First();
btn.Click += new EventHandler(Btn_Click);
}
}
int a = 0;
int counter=0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
Button btn = new Button();
btn.Location = new Point(0, 100);
btn.Text = "ADD";
btn.Name ="_B";
btn.Dock = DockStyle.Left;
btn.Click += new EventHandler(Btn_Click);
TextBox txt = new TextBox();
txt.Name = "_T";
txt.Location = new Point(500, 100);
txt.Dock = DockStyle.Left;
txt.Text = a.ToString();
panel3.Controls.Add(txt);
panel3.Controls.Add(btn);
foreach (var item in panel3.Controls.Find("_B", true))
{
item.Text = "ass";
}
}
private void Btn_Click(object sender, EventArgs e)
{
// MessageBox.Show(sender.ToString());
// throw new NotImplementedException();
var txtbx= panel3.Controls.Find("_T", true).First();
var btnbx = panel3.Controls.Find("_B", true).First();
a++;
// find[1].Dispose();
txtbx.Text = a.ToString();
}
}
}
答案 0 :(得分:0)
首先,您为每个TextBox和Button提供相同的Name属性,您不应该这样做。相反,例如:
btn.Name = "_B_"+ counter;
因此,按钮和文本框的名称将不同。在事件处理程序中:
private void Btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string index = btn.Name.Split('_')[2];
string tbName = "_T_" + index;
var txtbx= panel3.Controls.Find(tbName, true).First();
a++;
txtbx.Text = a.ToString();
}