从DDL中选择值时出错

时间:2011-04-06 20:20:36

标签: asp.net drop-down-menu datalist

我有datalist并且我有ddl,用户可以从ddl中选择值来绑定datalist。当用户选择值时,当我尝试在ddl中找到datalist时,此错误已显示

  

指数超出范围。一定是   非负和小于的大小   集合。参数名称:index

这里

DDLProduct2 = (DropDownList)DLProduct.Items[DLProduct.EditItemIndex].FindControl("DDlProduct");

所以请任何人帮助我。

private DropDownList DDLProduct2;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ProductByProductID();
            CategoryParentZero();


        }
    }
 protected void DDlProduct_SelectedIndexChanged(object sender, EventArgs e)
    {
        DDLProduct2 = (DropDownList)DLProduct.Items[DLProduct.EditItemIndex].FindControl("DDlProduct");
        if (DDLProduct2 != null)
        {
            if (DDLProduct2.SelectedIndex > 0)
            {
                using
                (SqlConnection conn = Connection.GetConnection())
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_GetProductsByProductID";
                    SqlParameter ParentID_Param = cmd.Parameters.Add("@ProductID", SqlDbType.Int);
                    ParentID_Param.Value = DDLProduct2.SelectedValue;
                    ;
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    da.Fill(dt);
                    DLProduct.DataSource = dt;
                    DLProduct.DataBind();

                }
            }
        }

    } 

1 个答案:

答案 0 :(得分:0)

DLProduct.EditItemIndex应该等于-1,因为没有编辑

只需在投掷错误的行

之前添加if DLProduct.EditItemIndex >= 0