Foemilod
Foemilod

Reputation: 125

How to populate a dataGridView with an array of user generated integers

With this:

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

It produces the data correctly, But it produces all the rows in the array with extra data that will not be useful, empty data.

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

Would like to remove unnecessary rows of data

Upvotes: 5

Views: 52843

Answers (5)

Hemant
Hemant

Reputation: 1

how to assign the collection for below situation:

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;

Upvotes: 0

Damith
Damith

Reputation: 63065

You can use LINQ to generate the datasource from a array.

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

Upvotes: 3

Jageen
Jageen

Reputation: 6365

You can have code like this also,

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

Output
enter image description here

Upvotes: 12

carbo18
carbo18

Reputation: 468

Take a look at this .NET / C# Binding IList<string> to a DataGridView

Setting the datasource to an array will not display anything. Basically the values need to have a named property and need to implement IList to be able to be used as a DataSource. Something like this should do your bidding.

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

Upvotes: 5

Saeid Alizade
Saeid Alizade

Reputation: 863

Try this:

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

gvMain is a GridView, You can Add user generated array instead of ints.

Upvotes: 2

Related Questions