查找控件在动态创建的表行c#

本文关键字:创建 控件 动态 查找 | 更新日期: 2023-09-27 18:13:12

我已经使用如下所示的一个函数动态地创建了一个表行。

Table The_Table = Invoice_Table;
TableRow new_Item_Row = new TableRow();
The_Table.Rows.Add(new_Item_Row);
TableCell new_type = new TableCell();
TableCell new_item = new TableCell();
TableCell new_amount = new TableCell();
DropDownList type_List = new DropDownList();
type_List.ID = "type_List";
   ListItem Cash = new ListItem();
   Cash.Value="Cash";
   Cash.Text="Cash/Cheque";
   ListItem IVoi = new ListItem();
   IVoi.Value="IVoi";
   IVoi.Text="Invoice";
   type_List.Items.Add(Cash);
   type_List.Items.Add(IVoi);
TextBox item_Text = new TextBox();
item_Text.ID = "item_Text";
TextBox amount_Text = new TextBox();
amount_Text.ID = "amount_Text";
new_type.Controls.Add(type_List);
new_item.Controls.Add(item_Text);
new_amount.Controls.Add(amount_Text);
new_Item_Row.Cells.Add(new_type);
new_Item_Row.Cells.Add(new_item);
new_Item_Row.Cells.Add(new_amount);

之后,我尝试在不同的函数

中使用以下命令访问该控件
 DropDownList type_L = Invoice_Table.FindControl("type_List") as DropDownList;
 TextBox amount_p = Invoice_Table.FindControl("amount_Text") as TextBox;
 TextBox Item_T = Invoice_Table.FindControl("item_Text") as TextBox;

但是它正在返回"对象引用未设置为对象的实例。"

我想这是因为它找不到控件?但我不知道该怎么解决。

抱歉添加新单元格的混乱…我是新手,我不知道还有什么更好的方法。

查找控件在动态创建的表行c#

问题是FindControl不是递归的。你必须在TableCell实例上调用它,而不是在Table本身上。

TextBox amount_p = new_amount.FindControl("amount_Text") as TextBox;