Reputation: 3213
I want to have a grid view on my form that when I click a button it will load some test data into the DataGridView.
The name is called grid in the properties. For some reason my DataTable is not being loaded into the DataGridView and thus will not show on my form.
Code:
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;
}
Upvotes: 0
Views: 262
Reputation: 26209
Problem : You are not adding the DataGridView
Control on the Form which was created at the runtime
Solution : You need to add the DataGridView
to the Form
Add these 2 statements :
grid1.Location = new Point(100,100);//x and y axis
this.Controls.Add(grid1);
OR
if you create DataGridView
in Form Designer you can use the same DataGridView
without creating the new one in runtime to bind the data as below:
Replace This:
grid.DataSource = table;
With This:
dataGridView1.DataSource = table;
EDIT: changing width of columns from Designer
Upvotes: 2
Reputation: 242
try this
i assume that grid already in your form not add run time
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;
and if you add gridcontrol on button click event then
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;
Upvotes: 4