简体   繁体   中英

How to bind data to the columns in C# Windows Forms grid view, which are stored in rows in SQL table

Please refer the images. How to bind the SQL table data which are stored in rows in to data grid view (C# Windows Forms) as columns. Also I have created column[0] as a hard coded column. I need to bind these data which is coming from SQL to column 1 . Please help me. Thanks in advance . :-)

SQL表 期待C#网格视图

You can create a method which rotate the DataTable and swap columns and rows this way:

public DataTable Rotate(DataTable table)
{
    var output = new DataTable();
    int i = 1;
    output.Columns.Add(" ");
    foreach (DataRow r in table.Rows)
        output.Columns.Add((i++).ToString());
    foreach (DataColumn c in table.Columns)
    {
        var list = new List<object>();
        list.Add(c.ColumnName);
        var x = table.AsEnumerable().Select(r => string.Format("{0}", r[c])).ToArray();
        list.AddRange(x);
        output.Rows.Add(list.ToArray());
    }
    return output;
}

Then you can use it to rotate the original table:

在此处输入图片说明

to rotated table:

在此处输入图片说明

or even with some simple tricks like this:

在此处输入图片说明

Here is the code which I used to create the example:

var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Date", typeof(DateTime));
dt.Rows.Add(100, "A", DateTime.Now);
dt.Rows.Add(200, "B", DateTime.Now.AddDays(1));
dt.Rows.Add(300, "C", DateTime.Now.AddDays(2));
dt.Rows.Add(400, "D", DateTime.Now.AddDays(3));
this.dataGridView1.DataSource = dt;
this.dataGridView2.DataSource = Rotate(dt);
//To hide column headers and show Id,Name,Date on rows headers, un-comment following codes:
//dataGridView2.ColumnHeadersVisible = false;
//dataGridView2.Columns[0].Visible = false;
//for (int i = 0; i < dataGridView2.Rows.Count; i++)
//    dataGridView2.Rows[i].HeaderCell.Value = dataGridView2.Rows[i].Cells[0].Value;

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