0

I need to insert data from array to a DataGridView, but when I give handle to DataGridView from list, everything what I get is count of elements in array.

public static class Globalne
{
   public static List<string> Mena = new List<string>();
   public static string[] stringy = { "1", "2", "3", "4", "5" };
}

This is the program

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.ColumnCount = 3;
    dataGridView1.Columns[0].Name = "Name";
    dataGridView1.Columns[1].Name = "Surname";
    dataGridView1.DataSource =  Globalne.stringy;
}
2
  • You defined 3 columns to show a string array which can not bind to any of those columns. What do you expect? What are you going to do? Commented Oct 8, 2017 at 15:11
  • I want insert array list to one column Commented Oct 8, 2017 at 15:16

1 Answer 1

1

To solve the problem, consider these notes:

  • To bind DataGridView to an array of string, you should shape the array to a List containing a property.
  • Each column of the DataGridView will show value of the property of the DataSource which have the same property name as the column's DataPropertyName.

Example

string[] stringy = { "A", "B", "C", "D", "E" };
dataGridView1.Columns.Add("C1", "Header 1");
dataGridView1.Columns["C1"].DataPropertyName = "Property1";
dataGridView1.Columns.Add("C2", "Header 2");
dataGridView1.DataSource = stringy.Select(x => new { Property1 = x }).ToList();

And here is the result:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

This is exactly what I wanted ! Thank you so much !
In general I recommend you to use a BindingList<T> or a DataTable for editing data in DataGridView rather that such array.
But how can I make that same with next column and with another list array ? When I try something everything what I get is rewrite first column, what is otherwise in last line ?
Each column of the DataGridView will show value of the property of the DataSource which have the same property name as the column's DataPropertyName. For example, for the second column, set it's data property name to Property2 and then when shaping the string list, select ` new { Property2 = x }. That's why I told you it's better to use BindingList<T>` or DataTable rather than array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.