I had datalist and I had ddl on it and user can select value from ddl to bind datalist. When I tried to find ddl in datalist when user select value, this error apeared
Index was out of range. Must be
non-negative and less than the size of
the collection. Parameter name: index
here
DDLProduct2 = (DropDownList)DLProduct.Items[DLProduct.EditItemIndex].FindControl("DDlProduct");
so please any one help me.
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();
}
}
}
}
DLProduct.EditItemIndex should be equal to -1 because the is nothing edited
just add an
if DLProduct.EditItemIndex >= 0before the line throwing the error