如何将DataTable设置为DataGridView,以便DataTable中的数据将显示在DataGridView中?

时间:2014-02-27 17:40:52

标签: c# winforms

我希望在我的表单上有一个网格视图,当我单击一个按钮时,它会将一些测试数据加载到DataGridView中。

名称在属性中称为网格。由于某种原因,我的DataTable没有加载到DataGridView中,因此不会显示在我的表单上。

代码:

private void button3_Click(object sender, EventArgs e)
    {
        DataTable table = new DataTable();
        table.Columns.Add("Dosage", typeof(int));
        table.Columns.Add("Drug", typeof(string));
        table.Columns.Add("Patient", typeof(string));
        table.Columns.Add("Date", typeof(DateTime));

        table.Rows.Add(25, "Indocin", "David", DateTime.Now);
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

        DataGridView grid = new DataGridView();
        grid.DataSource = table;
    }

enter image description here

2 个答案:

答案 0 :(得分:4)

试试这个

我假设你的表格中的网格没有添加运行时间

table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

dataGridView1.DataSource = table;

如果你在按钮点击事件上添加gridcontrol,那么

    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

    DataGridView grid = new DataGridView();
    grid.Location = new Point(50, 50);
    this.Controls.Add(grid);
    grid.DataSource = table;

答案 1 :(得分:2)

问题:您没有在运行时创建的表单上添加DataGridView控件

解决方案:您需要将DataGridView添加到表单

添加以下两个陈述:

    grid1.Location = new Point(100,100);//x and y axis
    this.Controls.Add(grid1);

OR

如果您在表单设计器中创建DataGridView,则可以使用相同的DataGridView而无需在运行时创建新的grid.DataSource = table; 来绑定数据,如下所示:

替换它:

dataGridView1.DataSource = table;

有了这个:

{{1}}

编辑:更改Designer

中列的宽度

enter image description here