天天看點

關于動态建立控件,第二次指派不能顯示解決辦法

動态建立控件并顯示在窗體上的panel上

Label[] lb;

TextBox[] txtInput;

lb = null;

txtInput = null;

lb = new Label[ds.Tables[0].Rows.Count];

txtInput = new TextBox[ds.Tables[0].Rows.Count];

foreach (Control ct in this.panel_Button.Controls)

{

try

{

string strConvert= ((TextBox)ct).Text ;

ct.Text="";

}

catch

{

}

}

for (int k = 0; k < ds.Tables[0].Rows.Count; k++)

{

int x = GetColIndex(k + 1, 3);//列

int y = GetRowIndex(k + 1, 3);//行

lb[k] = new Label();

lb[k].AutoSize = true;

lb[k].Name = "lb" + ds.Tables[0].Rows[k]["WorkItemID"].ToString().Trim();

lb[k].Left = (x - 1) * 300 + 10;

lb[k].Top = y * 30 + 5;

lb[k].Parent = this.panel_Button;

lb[k].Tag = Convert.ToInt16(ds.Tables[0].Rows[k]["WorkItemID"].ToString());

lb[k].Text = ds.Tables[0].Rows[k]["WorkItemDes"].ToString().Trim();

this.panel_Button.Controls.Add(lb[k]);

txtInput[k] = new TextBox();

txtInput[k].Name = "txtBox" + ds.Tables[0].Rows[k]["WorkItemID"].ToString().Trim();

txtInput[k].Left = (x - 1) * 300 + 10 + 110;

txtInput[k].Top = y * 30 + 5 - 2;

txtInput[k].Width = 150;

txtInput[k].Parent = this.panel_Button;

txtInput[k].Tag = Convert.ToInt16(ds.Tables[0].Rows[k]["WorkItemID"].ToString()) * 3;

txtInput[k].Text = "";

this.panel_Button.Controls.Add(txtInput[k]);

this.panel_Button.Refresh();

txtInput[k].Refresh();

}

tsbSelectDepartMent.Enabled = true;

第一次能正常指派并顯示所指派

第二次卻不能正常指派并顯示所指派

解決辦法:

foreach (Control cl in this.panel_Button.Controls)

                {

                    if (cl.GetType() == typeof(System.Windows.Forms.TextBox))

                    {

                        if (cl.Name == "txtBox08")//根據控件名稱查找并指派

                        {

                            cl.Text =frm.SelectDpID ;

                        }

                    }

                }