从winforms中的db字段自动创建输入UI?

时间:2012-06-26 18:01:30

标签: winforms entity-framework data-binding datagridview datasource

我正在尝试在winforms中创建一个表单,以便将记录添加到数据库,例如新客户。我正在使用实体框架。

直到今天我所做的是从实体框架生成的类中创建一个新的空“Customer”对象。然后我将这个空对象添加到列表中,并将列表设置为datagridview的数据源。

这样我就可以在网格中自动输入所有必需的字段来输入数据库。 一切正常。

但是现在,客户想要一个更好的UI设计 - 看起来像网页中的联系表单而不是网格行。

如何自动创建类似的内容,就像我使用datagridview一样,根据数据库结构自动创建所有输入字段而不创建手动标签和文本框?

2 个答案:

答案 0 :(得分:0)

最好的办法是保留DataGridView但覆盖样式,使其看起来远离网格,更像是老板的期望。

实现这一目标的一些建议:

  • 删除每行之间的行。
  • 删除标题和网格边框。
  • 为每行和每列添加大量填充,以使每个条目间隔开 出。对于更高级的东西,您可能需要覆盖Paint 网格的一些控制方法。

答案 1 :(得分:0)

我最终迭代网格并在每次迭代中创建文本框和标签。

void Generate_TextBoxes()
{
  // top of textboxes
  int current_top=150;
  int current_left = 1000;

  // index used to match between each textbox and the properate column in grid
  int my_index = -1;

  // iterate the grid and create textbox for each column
  foreach (DataGridViewColumn col in dataGridView_add_customer.Columns)
  {
    my_index++;

    // generate textboxes only for visible columns
    if (col.Visible == true)
    {
      // increase the top each time for space between textboxes
      current_top += 40;

      // create a second column of textboxes (not all of them in 1 long column)
      if (my_index == 6) { current_top = 190; current_left = 450; }


      TextBox t = new TextBox();
      t.Top = current_top;
      t.Left = current_left;
      t.Width = 170;
      t.TextChanged +=new EventHandler(t_TextChanged);
      // give an 'id' for each textbox with the corresponding index of the grid
      t.Name = my_index.ToString();

      Label l = new Label();
      l.Text = col.HeaderCell.Value.ToString();
      l.Top = current_top;
      l.Left = current_left + 190;

      this.Controls.Add(l);
      this.Controls.Add(t);
}

以及将文本框绑定到网格的函数:

void t_TextChanged(object sender, EventArgs e)
{
  // create a reference in order to be able to access grid properties such as rows..
  TextBox tt = (TextBox)sender;

  // access the correct cell in the grid using the Name property you gave to the textbox (it was name=current_index..)
  dataGridView_add_customer.Rows[0].Cells[int.Parse(tt.Name)].Value = tt.Text;

}