之前一个项目用到许多个label,现在需要点击label实现对label文本进行编辑,可以直接把label换成textbox,但由于label所用较多,改起来较为麻烦,故此用以下方法。
思想:label本身的文本是不可编辑的,故此使用一个textbox,在点击label后,将textbox的位置设置为和label一样,同时将label隐藏,在textbox中输入文本后,将值再赋值给label,textbox隐藏,label显示,即可实现label的编辑效果。
写了个测试的小例子:
效果如下图:
public partial class Form1 : Form
{
/// <summary>
/// 用于保存label编辑之前的文本
/// </summary>
string oldstr;
/// <summary>
/// 用于表示当前编辑的是哪个label的标志位
/// </summary>
int lbl;
Control[] LabelIO;
public Form1()
{
InitializeComponent();
textBox1.Visible = false;
LabelIO = new Control[] {label1,label2,label3,label4 ,label5};
}
private void label1_Click(object sender, EventArgs e)
{
lbl = 0;
textBox1.Visible = true;
textBox1.Location = label1.Location;
}
private void label2_Click(object sender, EventArgs e)
{
lbl = 1;
textBox1.Visible = true;
textBox1.Location = label2.Location;
}
private void label3_Click(object sender, EventArgs e)
{
lbl = 2;
textBox1.Visible = true;
textBox1.Location = label3.Location;
}
private void label4_Click(object sender, EventArgs e)
{
lbl = 3;
textBox1.Visible = true;
textBox1.Location = label4.Location;
}
private void label5_Click(object sender, EventArgs e)
{
lbl = 4;
textBox1.Visible = true;
textBox1.Location = label5.Location;
}
private void textBox1_LocationChanged(object sender, EventArgs e)
{
for (int i = 0; i < LabelIO.Length; i++)
{
if (textBox1.Location == LabelIO[i].Location)
{
oldstr = LabelIO[i].Text;
textBox1.Text = LabelIO[i].Text;
textBox1.Width = LabelIO[i].Width;
textBox1.SelectAll();
}
if (lbl==i)
{
LabelIO[i].Visible = false;
}
else
{
LabelIO[i].Visible = true;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string str = textBox1.Text.Replace(" ",""); //避免只输入空格,导致显示空文本的情况
if (textBox1.Text==null||textBox1.Text==""||str=="")
{
LabelIO[lbl].Text = oldstr;
}
else
{
LabelIO[lbl].Text = textBox1.Text;
}
}
}