简体   繁体   中英

Data Grid View — binding columns to list

My project in c# contains dataGridView and I have a object containing data.

public class Data
{
    public List<string> list {get;set;}

}

The data is initialized at program startup and the length of list can change. I want to bind the gridView to object that when gridView show each columns in gridview is bound to list in data object like this:

if list count = 3 , than i want gridView contains 3 columns - column0 bind to list[0], column01 bind to list[1], and so on.

i think that i need to bind gridView when form is loading , but how can i do this in my code?

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true" >
</asp:GridView>

private static Random _rnd = new Random(DateTime.Now.Millisecond);

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var columns = _rnd.Next(3, 10);
        var data = new { list = Enumerable.Range(1, columns).ToList() };

        GridView1.DataSource = data.list.Pivot();
        GridView1.DataBind();
    }
}


public static class Extensions
{
    public static DataTable Pivot<T>(this IEnumerable<T> list)
    {
        if (list == null)
            throw new ArgumentNullException("list");

        DataTable result = new DataTable();
        for (int index = 0; index < list.Count(); index++)
        {
            DataColumn column = new DataColumn(string.Format("Column{0}", index), typeof(T));
            result.Columns.Add(column);
        }

        var dataRow = result.NewRow().ItemArray = list.Select(item => (object)item).ToArray();
        result.Rows.Add(dataRow);

        return 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