【问题标题】:How to populate a dataGridView with an array of user generated integers如何使用用户生成的整数数组填充 dataGridView
【发布时间】:2013-09-16 03:50:36
【问题描述】:

有了这个:

dataGridView.DataSource = theData.Select((x, index) =>
    new { CreatureRoll = x, CreatureLabel = index}).OrderByDescending(x =>    x.CreatureRoll).ToList();

它会正确生成数据,但它会生成数组中的所有行,其中包含没有用的额外数据,即空数据。

img http://s21.postimg.org/t3f34aa43/list_Result.jpg?noCache=1379353500

想要删除不必要的数据行

【问题讨论】:

  • 要求代码的问题必须表明对所解决问题的最低理解。包括尝试过的解决方案、它们为什么不起作用以及预期的结果。
  • 提供更多细节,比如它有多少行?

标签: c# arrays datagridview


【解决方案1】:

你也可以有这样的代码,

dataGridView1.Columns.Add("Index", "Index");
dataGridView1.Columns.Add("Value", "Dice Value");
int[] theData = new int[] { 5, 2, 1, 5, 4, 1, 3, 1};

for (int i = 0; i < theData.Length; i++)
{
     dataGridView1.Rows.Add(new object[] { i+1, theData[i] });
}

输出

【讨论】:

  • 所以,这对我有用,但我还需要添加到列表中,那就是每个卷的标签。
  • 你的意思是索引你想要标签文本?
  • 好吧,我有一个计数器,计数器“creatureLabel”标记用户在原始文本框中生成的每个卷。一世。 e. ("\n" + 生物标签 + "." + theData[i] + " ");
  • 好吧,我假设你已经成功地对数据进行了排序,并且你有一个字符串数组,比如“2. 17 1. 14 4. 11 3. 5 5. 2” 不,你想在网格上显示它查看与,对吧?
  • 是的,这就是我想要的。 Damith 的代码也在正确的轨道上
【解决方案2】:

看看这个.NET / C# Binding IList<string> to a DataGridView

将数据源设置为数组不会显示任何内容。基本上,这些值需要有一个命名属性,并且需要实现 IList 才能用作数据源。像这样的东西应该让你出价。

var array = new int[] { 3, 4, 4, 5, 6, 7, 8 };
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = array.Select(x => new { IntValue = x }).ToList(); 

【讨论】:

    【解决方案3】:

    您可以使用 LINQ 从数组中生成数据源。

    int[] theData = new int[] { 14, 17, 5, 11, 2 };
    dataGridView1.DataSource = theData.Where(x => x>0).Select((x, index) =>
        new { RecNo = index + 1, ColumnName = x }).OrderByDescending(x => x.ColumnName).ToList();
    

    【讨论】:

    • 由于我的数组长度为 100,我最终得到了一堆不必要的额外行。我有什么办法可以将要生成的行数设置为等于数组中写入的数据量?
    • 您最好使用List&lt;int&gt; 并为其添加值。你能用你的代码更新问题吗?
    • 使用数组,还可以使用Where 方法(已经在答案中),过滤哪些值不会进入网格。
    【解决方案4】:

    试试这个:

    int[] ints = new int[] { 1, 2, 3, 4, 5 };
    gvMain.DataSource = ints;
    gvMain.DataBind();
    

    gvMain 是一个 GridView,您可以添加用户生成的数组而不是 ints

    【讨论】:

      【解决方案5】:

      如何为以下情况分配集合:

      foreach (DataRow dr in dropDT.Rows)
      {
           values.Add(dr[0].ToString());
      }
      
      dataGridView1.Rows[e.RowIndex].Cells[4].Value = values;
      dataGridView1.Rows[e.RowIndex].Cells[4].Value = values;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2017-09-16
        • 1970-01-01
        • 2020-02-08
        相关资源
        最近更新 更多