动态添加的列表框事件未触发

时间:2012-03-29 06:20:30

标签: c# asp.net webforms

我的问题是当我点击一个列表框时,应该显示另一个列表框,其中包含动态相关的值。将显示列表框,但不会触发列表框事件。 lb_SelectedIndexChanged事件未触发。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        SqlCommand com = new SqlCommand("select EmpId,EmpName from OrgChart where      ManagerID=0", con);
        con.Open();
        SqlDataReader dr = com.ExecuteReader();
        int i=0;

        while (dr.Read())
        {
            empid[i] = Convert.ToInt32(dr[0].ToString());
            ename[i] = dr[1].ToString();
            i++;
        }

        for(int j=0;j<i;j++)
            ListBox1.Items.Add(empid[j]+"-"+ename[j]);

        ListBox1.Items.Add("create new");
    }
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Table1.Visible =false;
    Table2.Visible = false;
    string comand = ListBox1.SelectedValue.ToString();
    if (comand == "create new")
    {
        Table1.Visible = true;
    }
    else
    {
        Table2.Visible = true;
        string[] emp = comand.Split('-');
        getdetails(Convert.ToInt32(emp[0]));
    }
}

static ListBox lb = new ListBox();           
void getdetails(int empid)
{
    managerid = empid;
    con.Open();
    com = new SqlCommand("select EmpId,EmpName from OrgChart where ManagerID=" + managerid + "", con);
    dr = com.ExecuteReader();

    lb.ID = "lb1";
    lb.AutoPostBack = true;

    while (dr.Read())
    {
        lb.Items.Add(dr[0].ToString() + "-" + dr[1].ToString());
    }

    lb.Items.Add("create new");

    lb.SelectedIndexChanged += new EventHandler(this.lb_SelectedIndexChanged);

    this.Controls.Add(lb);
}

void lb_SelectedIndexChanged(object sender, EventArgs e)
{
    Table1.Visible = false;
    Table2.Visible = false;
    getdetails(managerid);
    string comand = ((ListBox)sender).SelectedValue.ToString();
    if (comand == "create new")
    {
        Table1.Visible = true;
    }
    else
    {
        Table2.Visible = true;
        string[] emp = comand.Split('-');
        getdetails(Convert.ToInt32(emp[0]));
    }

2 个答案:

答案 0 :(得分:1)

您需要将 .AutoPostBack 属性设置为true。

在你的代码示例中就像是

if (!IsPostBack)
{
   //...
   ListBox1.AutoPostBack = true;
   //...

}

答案 1 :(得分:1)

添加列表oninit事件,因为某些事件不会通过onload事件启动