如何使用用户生成的整数数组填充dataGridView

时间:2013-09-16 03:50:36

标签: c# arrays datagridview

有了这个:

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

想要删除不必要的数据行

5 个答案:

答案 0 :(得分:8)

你也可以拥有这样的代码,

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

输出
enter image description here

答案 1 :(得分:5)

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

将数据源设置为数组不会显示任何内容。基本上,值需要具有命名属性,并且需要实现IList才能用作DataSource。这样的事情应该是你的出价。

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

答案 2 :(得分: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();

enter image description here

答案 3 :(得分:2)

试试这个:

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

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

答案 4 :(得分:0)

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

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;
相关问题