嗨,大家好我在C#中创建动态控件,我遇到了删除功能的问题。 [英] Hi Guys I Am Creating Dynamic Controlls In C#, I Got Problems With My Remove Function.
本文介绍了嗨,大家好我在C#中创建动态控件,我遇到了删除功能的问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个文本框,下拉列表和一个按钮,我想点击一个按钮删除该行。我尝试了不同的东西,但我无法让它工作,我最接近的是删除最后一行。这里是我的代码。
这里是创建控件
i am making a textbox, dropdown and a button and i want to make whn i click a button it removes that row. I have tried different thing but i can't get it to work, the closest i have been is removing last row. here my code.
here is were creating the controlls
int rowCount = Convert.ToInt32(txtDeltager.Text);
for (int i = 0; i < rowCount; i++)
{
int count = int.Parse(hdnCount.Value);
count++;
hdnCount.Value = count.ToString();
TextBox tb = new TextBox();
tb.ID = "txtbox" + count.ToString();
tb.Width = 200;
tb.CssClass = "txtPas";
DropDownList ddl = new DropDownList();
ddl.ID = "ddl" + count.ToString();
ddl.CssClass = "ddlpas";
Button btnRe = new Button();
btnRe.Text = "Slet";
btnRe.ID = "btnRe" + count.ToString();
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc.Controls.Add(tb);
tc.Controls.Add(ddl);
tc.Controls.Add(btnRe);
tr.Cells.Add(tc);
tblMain.Rows.Add(tr);
btnRe.Click += delegate
{
// NOTE: The code below here were i try to make a remove function
for (i = 0; i <= rowCount; i--)
{
if (tblMain.Controls.Contains(tr))
{
tblMain.Controls.Remove(tr);
tr.Dispose();
}
}
};
和代码是我重新创建控件所以我保持viewState
and the code were i recreating the controls so i keep the viewState
// Recreate the textboxes on each postback
for (int i = 2; i <= count; i++)
{
TextBox tb = new TextBox();
tb.ID = "txtbox" + i.ToString();
tb.Width = 200;
tb.CssClass = "txtPas";
tb.Text = Request.Form["txtbox" + i.ToString()];
DropDownList ddl = new DropDownList();
ddl.ID = "ddl" + i.ToString();
ddl.CssClass = "ddlpas";
Button btnRe = new Button();
btnRe.Text = "Slet";
btnRe.ID = "btnRe" + i.ToString();
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc.Controls.Add(tb);
tc.Controls.Add(ddl);
tc.Controls.Add(btnRe);
tr.Cells.Add(tc);
tblMain.Rows.Add(tr);
btnRe.Click += delegate
{
// NOTE: The code below here were i try to make a remove function
for (i = 2; i <= count; i--)
{
if (tblMain.Controls.Contains(tr))
{
tblMain.Controls.Remove(tr);
tr.Dispose();
}
}
};
推荐答案
如果你想要删除某些东西,你必须采取相反的方式而不是创建。
在你的情况下:
- 从Button中删除处理程序(委托)(btnRe)
- 从控件集合中删除并处理控件tc
- 从tr中移除tc
如果你这样做它会起作用。
用于实现这样的代码我更喜欢创建一个方法CreateControls和另一个方法RemoveControls。这样会更清楚。
If you want to remove something you have to do it the other way round than creating.
In your case :
- remove the handler (delegate) from the Button (btnRe)
- remove and dispose the controls out of the controls-collection from tc
- remove tc from tr
If you do it like this it will work.
For realizing such code I would prefer to create a method "CreateControls" and another method "RemoveControls". That would be clearer arranged.
这篇关于嗨,大家好我在C#中创建动态控件,我遇到了删除功能的问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文