在动态创建的表单上填充动态创建的DataGridView [英] Fill a dynamically created DataGridView on a dynamically created form
问题描述
我有一个带有菜单的MDI表单,该表单在加载表单时为DataSet中的每个表创建一个MenuItem.目的是让用户选择一个MenuItem并打开相应的表单,添加一些布局项和一个DataGridView来显示 基础表中的数据.
I have an MDI form with a Menu that creates a MenuItem for each of the Tables in the DataSet when the Form Loads. The intention is that the user to selects a MenuItem and the corresponding form opens, adding some layout items and a DataGridView that displays the Data from the underlying table.
我已经设法在动态创建的表单上创建了DataGridView,并且已经设法将其DataBinding设置为用户在MenuItem中选择的表. (即,我可以在网格顶部看到正确的列标题)
I have managed to create the DataGridView on the dynamically created form and have managed to set its DataBinding to the Table selected by the user in the MenuItem. (i.e I can see the correct column titles at the top of the grid)
我想知道如何用数据库中的数据填充DataGridView.我认为这与TableAdapters有关,但事实证明它们很神秘.
I wish to know how to Fill the DataGridView with the data in my database. I figured it has something to do with TableAdapters but they are proving to be mysterious.
private void formLoad(String formName,string formTag)
{
//Create a new form
Form frm = new Form();
frm.Text = "Manage " + formName + " (" + formTag + ")";
frm.Size = new Size(900, 600);
frm.MdiParent = this;
frm.Show();
//Add Table to form
TableLayoutPanel tlpAdd = new TableLayoutPanel()
{
Dock = DockStyle.Fill,
RowCount = 2,
ColumnCount = 2,
CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
};
frm.Controls.Add(tlpAdd);
//Data Grid
DataGrid grdAdd = new DataGrid();
DataSet ds = this.myDataSet1;
grdAdd.SetDataBinding(ds, formTag);
grdAdd.Name = formTag;
grdAdd.AutoSize = true;
grdAdd.Dock = DockStyle.Fill;
tlpAdd.SetRow(grdAdd, 1);
tlpAdd.SetColumn(grdAdd, 2);
tlpAdd.SetRowSpan(grdAdd, 2);
tlpAdd.Controls.Add(grdAdd);
//Add FlowLayoutPannel for buttons
FlowLayoutPanel flwAdd = new FlowLayoutPanel()
{
//AutoSize = true,
Size = new Size(600, 25),
Dock = DockStyle.Bottom,
FlowDirection = FlowDirection.LeftToRight
};
tlpAdd.Controls.Add(flwAdd);
tlpAdd.SetColumnSpan(flwAdd, 2);
tlpAdd.SetColumn(flwAdd, 1);
tlpAdd.SetRow(flwAdd, 2);
//Add Data management Buttons etc to flow layout
}
推荐答案
尝试一下
public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
// 1
// Open connection
using (SqlCeConnection c = new SqlCeConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlCeDataAdapter a = new SqlCeDataAdapter(
"SELECT * FROM Animals", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
}
}
这篇关于在动态创建的表单上填充动态创建的DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!