0

我試圖在Winforms中創建一個窗體,將記錄添加到數據庫,例如新客戶。我正在使用實體框架。從winforms中的db字段自動創建輸入用戶界面?

我直到今天所做的工作是從實體框架生成的類中創建一個新的空「客戶」對象。然後我將這個空對象添加到列表中,並將列表設置爲datagridview的數據源。

這樣我自動在網格中輸入所有必需的字段到數據庫。 一切正常。

但是現在,客戶希望爲用戶界面提供更好的設計 - 看起來像網頁中的聯繫表單,而不是網格行。

我該如何自動創建類似於datagridview的東西,根據數據庫結構自動創建所有輸入字段,而無需手動創建標籤和文本框?

回答

0

最好的辦法是保留DataGridView,但重寫樣式,以使其看起來遠離網格,更像是您的老闆所期待的。

一些建議,以實現這一目標:

  • 刪除每行之間的線。
  • 刪除標題和網格邊框。
  • 爲每行和每列添加大量填充,因此每個條目的間隔爲 。對於更高級的東西,您可能需要重寫網格的某些控件的Paint 方法。
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; 

}

相關問題