【问题标题】:DataGridView: Add new row using an array or List<t>DataGridView:使用数组或 List<t> 添加新行
【发布时间】:2013-01-11 15:37:12
【问题描述】:

我的表单中有两个列表框元素。 listbox1 中的项目代表我的 DataGridView 中的列, 我的 listbox2 中的项目代表我的 DataGridView 中的行。

foreach (var el in listBox1Elements)
{
// code...
dataGridView1.Columns.Add(col);
}

由于可以添加或删除 listbox1 中的项目,我当前的解决方案存在问题。

dataGridView1.Rows.Add("test","some","data","even","more","data");

我想知道是否有使用列表的解决方案。 然后我的代码可能看起来像这样:

foreach (var el in listBox2Elements)
{
   myList.add("some text");
}
dataGridView1.Rows.Add(myList);

【问题讨论】:

    标签: c# list datagridview


    【解决方案1】:

    类似

            foreach (var el in listBox2Elements)
                myList.add("some text");
    
            foreach (var item in myList)
                dataGridView1.Rows.Add(item.., item.., item..);
    

    dataGridView1.DataSource = myList.ToList()
    

    【讨论】:

      【解决方案2】:

      怎么样:

      foreach (var el in listBox2Elements)
      {
         myList.add("some text");
      }
      dataGridView1.Rows.Add(myList.ToArray());
      

      【讨论】:

        【解决方案3】:

        好吧,如果没有 store 对象,那是一项艰巨的任务。 你可以很容易地去那里:

        //Not taking guarantee for this approach
        Store.DataSource.add(new object[]{"some text"});
        Store.DataBind();
        

        或者你定义一个新的数据源对象并用列表项(通过循环)填充它,然后再做一次:

        (list<string>) data_list.add("some text");
        //repopulate data object and set a Store.DataSource;
        Store.dataBind();
        

        对于删除对象,您可以从 list&lt;string&gt; 项目中删除它们并像上面一样更新商店

        //population for the data object:
        for(int x=0; x<= data_list.length(); x++)
        {
         data.add(new object[]{data_list[x]});
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-02
          相关资源
          最近更新 更多