简体   繁体   中英

How to insert data from list array to datagridview?

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

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM