无法在C#中的Datagridview中显示DataTable的内容

时间:2010-01-21 10:15:49

标签: c#-2.0

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

命名空间WindowsFormsApplication1 {     公共部分类Form1:表格     {         公共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.Add(row);


        }


    }

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


}

}

1 个答案:

答案 0 :(得分:1)

您没有调用CreateDataTable()方法或dataGridView1.DataBind()方法。我修改了您的示例以从CreateTable方法返回DataTable类型。

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