开发者

Can't display contents of a DataTable in a Datagridview in C#

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms;

namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

    public class Example
    {
        private void CreateTable()
        {

            //create datatable instance
            DataTable myTable = new DataTable();

            //create columns
            DataColumn col1 = new DataColumn("A");
            DataColumn col2 = new DataColumn("B");
            DataColumn col3 = new DataColumn("C");

            //define datacolumn data types
            col1.DataType = System.Type.GetType("System.Int");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");

            //add columns to table
            myTable.Columns.Add(col1);
            myTable.Columns.Add(col2);
            myTable.Columns.Add(col3);

            //create row in table
            DataRow row = myTable.NewRow();

            //populate columns with data
            row[col1] = "1001";
            row[col2] = "ABC";
            row[col3] = "HIJ";

            //add rows to table
            myTable.Rows.A开发者_开发技巧dd(row);


        }


    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        dataGridView1.DataSource = table;
    }


}

}


You were not calling the CreateDataTable() method or the dataGridView1.DataBind() method. I modified your example to return the DataTable type from the CreateTable method.

    private DataTable CreateTable()
    {

        //create datatable instance
        DataTable myTable = new DataTable();

        //create columns
        DataColumn col1 = new DataColumn("A");
        DataColumn col2 = new DataColumn("B");
        DataColumn col3 = new DataColumn("C");

        //define datacolumn data types
        col1.DataType = System.Type.GetType("System.Int");
        col2.DataType = System.Type.GetType("System.String");
        col3.DataType = System.Type.GetType("System.String");

        //add columns to table
        myTable.Columns.Add(col1);
        myTable.Columns.Add(col2);
        myTable.Columns.Add(col3);

        //create row in table
        DataRow row = myTable.NewRow();

        //populate columns with data
        row[col1] = "1001";
        row[col2] = "ABC";
        row[col3] = "HIJ";

        //add rows to table
        myTable.Rows.Add(row);

        return myTable;
    }

}

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = CreateTable();
    dataGridView1.DataBind();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜