當前位置:
首頁 > 知識 > 動態添加控制項及刪除

動態添加控制項及刪除

方法1:

int i = 0;

List<PhoneTextBox> list = new List<PhoneTextBox>();

private void btnAdd_Click(object sender, EventArgs e)

{

if (i >= 9)//只能添加9個(看自己需求)

{

return;

}

else

{

i = i + 1;

PhoneTextBox txtPhone = new PhoneTextBox();

txtPhone.Name = "txtPhone" + i;

txtPhone.Location = new Point(textBox4.Location.X, textBox4.Location.Y + textBox4.Height + txtPhone.Height * (i - 1) + 4);

txtPhone.BTNdel.Click += txtPhone_Click;

panel5.Controls.Add(txtPhone);

panel6.Location = new Point(panel6.Location.X, panel6.Location.Y + txtPhone.Height);

int n = txtPhone.Height;

list.Add(txtPhone);

//保證複製後的控制項都在原控制項下方顯示

txtPhone.BringToFront();

}

}

private void txtPhone_Click(object sender, EventArgs e)

{

Control c = (Control)sender;

string name = c.Parent.Name;

int nIndex = GetControlsName(c.Parent.Name);

for (int n = nIndex + 1; n < list.Count; n++)

{

list[n].Location = new Point(list[n].Location.X, list[n].Location.Y - list[n].Height);

}

list.RemoveAt(nIndex);

this.panel6.Location = new Point(this.panel6.Location.X, this.panel6.Location.Y - c.Height);

int b = c.Height;

panel5.Controls.Remove(c.Parent);

BindClick(c);

i = i - 1;

}

//根據控制項名稱找控制項索引

public int GetControlsName(string name)

{

int nIndex = 0;

for (int i = 0; i < list.Count; i++)

{

if (list[i].Name == name)

{

nIndex = i;

break;

}

}

return nIndex;

}

//綁定刪除控制項事件的代碼

private void BindClick(Control cl)

{

//保證如何在刪除和添加時能釋放資源(即可以緊跟在顯示的控制項後面顯示)

cl.Controls.Clear();

DisposeControls(cl);

//釋放資源

cl.Dispose();

}

//在清空控制項時如何釋放資源

private void DisposeControls(Control cParent)

{

foreach (Control c in cParent.Controls)

{

//DisposeControls(c);

c.Controls.Clear();

c.Dispose();

}

}

設計視圖和運行結果如圖

動態添加控制項及刪除

動態添加控制項及刪除

方法2:

在窗體加一個flowLayoutPanel1控制項還有一個button按鈕

private void btnadd_Click(object sender, EventArgs e)

{

string controlMark = Guid.NewGuid().ToString();

TextBox txt1 = new TextBox();

txt1.Name = "txt_" + controlMark;

txt1.Width = 120;

flowLayoutPanel1.Controls.Add(txt1);

Button btnDel = new Button();

btnDel.Name = "del_" + controlMark;

btnDel.Text = "刪除";

btnDel.Click += new EventHandler(delControl);

flowLayoutPanel1.Controls.Add(btnDel);

}

///點擊刪除按鈕刪除生成的控制項

public void delControl(object sender, EventArgs e)

{

Button btnAction = sender as Button;

string id = btnAction.Name.Split("_")[1];

foreach (Control c in this.flowLayoutPanel1.Controls)

{

if (c.Name == "txt_" + id)

{

flowLayoutPanel1.Controls.Remove(c);

}

}

foreach (Control c in this.flowLayoutPanel1.Controls)

{

if (c.Name == "del_" + id)

{

flowLayoutPanel1.Controls.Remove(c);

}

}

}

動態添加控制項及刪除

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

編譯過程的五個階段
使用Spark進行流式實時日誌分析系統的實現

TAG:程序員小新人學習 |