我长期以来一直在努力解决这个问题。
我在标签上添加了一个文本框和一个按钮。我把文字放在文本框中:
现在,我的问题是,如何删除单击按钮旁边的文本框并将所有文本框向下移动,这样我就不会得到任何空白区域。如果我按下第7个文本框旁边的按钮,我希望它看起来像这样:
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
//creates a textbox(t0) and a button(b0) on load
TextBox t0 = new TextBox();
t0.Name = "t0";
t0.Location = new Point(16, 12);
t0.Width = 200;
t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);
Button b0 = new Button();
b0.TabStop = false;
b0.Text = "x";
b0.Location = new Point(216, 11);
b0.Size = new System.Drawing.Size(20, 22);
b0.Click += new EventHandler(buttonclicked);
panel1.Controls.Add(t0);
panel1.Controls.Add(b0);
}
private new void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
//if I press tab in the last textbox it creates a new textbox(t + amount of textboxes) and button(b + amount of textboxes)
if (e.KeyData == Keys.Tab)
{
int counter2 = 0;
foreach (TextBox box in panel1.Controls.OfType<TextBox>())
{
counter2++;
}
counter2 = counter2 - 1;
string Name = "t" + Convert.ToString(counter2);
counter2++;
foreach (TextBox box in panel1.Controls.OfType<TextBox>())
{
if (Name == box.Name && box.Focused)
{
TextBox t0 = new TextBox();
Button b0 = new Button();
t0.Location = new Point(16, 12 + counter - panel1.VerticalScroll.Value);
t0.Width = 200;
t0.Name = "t" + Convert.ToString(counter2);
t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);
b0.TabStop = false;
b0.Text = "x";
b0.Name = "b" + Convert.ToString(counter2);
b0.Location = new Point(216, 11 + counter - panel1.VerticalScroll.Value);
b0.Size = new System.Drawing.Size(20, 22);
b0.Click += new EventHandler(buttonclicked);
panel1.Controls.Add(t0);
panel1.Controls.Add(b0);
counter = counter + 25;
}
}
}
}
private void buttonclicked(object sender, EventArgs e)
{
//Remove the textbox next to it.
}
感谢任何帮助
答案 0 :(得分:0)
我建议您使用TableLayoutPanel。将TableLayoutPanel上的GrowStyle
设置为AddRows
或AddColumns
,然后您可以添加/删除控件,它会自动调整大小。将每行的高度设置为略大于文本框高度的数字。将列宽设置为一个值,以便文本框和按钮可以适合它们。你需要2列。
您无需将控件的位置设置为静态位置。它们将由TableLayoutPanel
为您处理。
以下是如何为其添加新控件的方法。
yourTableLayoutPanel.Controls.Add(yourTextbox1, 0 /* Column Index */, 0 /* Row index */);