Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态创建多个列表框_C#_Asp.net_Listbox - Fatal编程技术网

C# 动态创建多个列表框

C# 动态创建多个列表框,c#,asp.net,listbox,C#,Asp.net,Listbox,我在SQL Server中有一个表,它给了我一个产品列表(PRODUCT)和产品类别(CAT)。现在,我将所有产品放在同一个列表框中: foreach (DataRow row in ds.Tables["ProductsTbl"].Rows) { string str = string.Format("{0}", row["PRODUCT"]); ListBox1.Items.Add(new ListItem(str)); } foreach(ds.Tables[“Produc

我在SQL Server中有一个表,它给了我一个产品列表(PRODUCT)和产品类别(CAT)。现在,我将所有产品放在同一个列表框中:

foreach (DataRow row in ds.Tables["ProductsTbl"].Rows) { string str = string.Format("{0}", row["PRODUCT"]); ListBox1.Items.Add(new ListItem(str)); } foreach(ds.Tables[“ProductsTbl”].Rows中的数据行) { string str=string.Format(“{0}”,行[“产品]); ListBox1.Items.Add(新列表项(str)); } 但我需要创建尽可能多的列表框,并根据类别分发这些产品。类别可能会被添加或删除,因此我需要动态创建它们

假设表中有5个产品属于类别1,4个产品属于类别2,7个产品属于类别3,我需要创建3个列表框。第一个有5项,第二个有4项,最后一个有7项。有什么想法吗? Thx

  • 订单
    ProductsTbl
    DataSet by
    categoryId
  • 每次遇到新的
    类别ID
  • 大概是这样的:

    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));
    }
    

    您甚至可以创建一个控件,使您能够调整外观,然后创建它的新实例,就像Joshia编写的代码一样


    上面是一个自定义控件的示例

    看起来不错,但是我能在那些动态创建的控件上触发事件吗?例如,对于每个列表框,我都有一个“全选”和“全选”按钮。对于客户端事件,可以使用jquery live函数。它将响应动态创建的元素。请参阅此链接