When user clicks specific Linkbutton, I would like to populate subcategories into another DATALIST (datalist2) control which will be inside datalist1 control.
But I am unable to retrieve ID of child DATALIST, I am getting error: The name datalist2 does not exist in the current context
BELOW IS THE SAMPLE code
/------------- CODE IN ASPX FILE ------------------
Expand|Select|Wrap|Line Numbers
- <asp:DataList ID="DataList1" runat="server" DataKeyField="CatID">
- <ItemTemplate>
- <li>
- <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Display" OnCommand="ImageButton_Command" CommandArgument='<%# Eval("CatID") %>'><%# Eval("Category") %></asp:LinkButton>
- </li>
- <ul>
- <asp:DataList ID="DataList2" runat="server">
- <ItemTemplate>
- <li>
- <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Display"><%# Eval("SubCategory") %></asp:LinkButton>
- </li>
- </ItemTemplate>
- </asp:DataList>
- </ul>
- </ItemTemplate>
- </asp:DataList>
- //------------- CODE IN CS FILE ------------
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- populateCatefories();
- }
- }
- protected void populateCatefories()
- {
- SqlConnection conn = new SqlConnection(clsConnection.connectionString());
- SqlCommand cmd = new SqlCommand();
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.CommandText = "GetAllCategories";
- cmd.Connection = conn;
- try
- {
- conn.Open();
- DataList1.DataSource = cmd.ExecuteReader();
- DataList1.DataKeyField = "CatID";
- DataList1.DataBind();
- }
- catch (Exception ex)
- {
- Response.Write(ex.ToString());
- }
- finally
- {
- conn.Close();
- cmd.Dispose();
- }
- }
- protected void ImageButton_Command(object sender, CommandEventArgs e)
- {
- if (e.CommandName == "Display")
- {
- getSubCategories(Convert.ToInt32(e.CommandArgument));
- }
- }
- protected void getSubCategories(int subCatID)
- {
- SqlConnection conn = new SqlConnection(clsConnection.connectionString());
- SqlCommand cmd = new SqlCommand();
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.CommandText = "getsubCategories";
- cmd.Parameters.AddWithValue("@CatID", subCatID);
- cmd.Connection = conn;
- try
- {
- conn.Open();
- //Control subDataList = FindControl("DataList2");
- DataList2.DataSource = cmd.ExecuteReader();
- DataList2.DataKeyField = "SubCatID";
- DataList2.DataBind();
- }
- catch (Exception ex)
- {
- Response.Write(ex.ToString());
- }
- finally
- {
- conn.Close();
- cmd.Dispose();
- }
- }
I have added below code to get ID of child datalist control, but it is getting errror: Object reference not set to an instance of an object.
Expand|Select|Wrap|Line Numbers
- DataList childDataList = (DataList)DataList1.FindControl("DataList2");
On some another site I found below code, but My code not able to recognize item element.
Expand|Select|Wrap|Line Numbers
- DataList dlSubChild = (DataList)e.Item.FindControl("dlSubChild")