0

I have a table in SQL Server which gives me a list of products (PRODUCT), and the products category (CAT). Right now I am putting all the products in the same ListBox:

foreach (DataRow row in ds.Tables["ProductsTbl"].Rows)
{
    string str = string.Format("{0}", row["PRODUCT"]);
    ListBox1.Items.Add(new ListItem(str));
}

But I need to create as many listboxes as there are categories, and distribute those products according to the category. Categories might be added or removed so I need to create them dynamically.

So lets say the table has 5 products in category 1, 4 products in category 2 and 7 products in category 3, I would need 3 Listboxes created. The first with 5 items, the second with 4 and the last one with 7 items. Any ideas ? Thx.

2 Answers 2

1
  1. Order ProductsTbl DataSet by categoryId
  2. Add a new listbox every time you encounter a new categoryId

Something like this:

var catId = ds.Tables["ProductsTbl"].Rows[0].categoryId;
var listBox = ListBox1;
foreach (DataRow row in ds.Tables["ProductsTbl"].Rows)
{
    if(catId != row.categoryId)
    {
        catId = row.categoryId;
        listBox = new ListBox();
        Panel1.Controls.Add(listBox);
    } 
    string str = string.Format("{0}", row["PRODUCT"]);
    listBox.Items.Add(new ListItem(str));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Looks good but would I be able to fire events on those dynamically created controls ? For instance, for each ListBox, I will have a "select all" and "unselect all" button.
Yes - for server events have a look at this link support.microsoft.com/kb/317794. For client events you can use a jquery live function. It will respond to dynamically created elements. See this link api.jquery.com/live
0

You could even create a control which would enable you to tweak the appearance and then create a new instance of it, much like the code by Joshia.

http://knol.google.com/k/creating-custom-controls-with-c-net#

Above is an example of custom controls

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.