2011-05-13 2 views
1

내가 원하는 것은 사용자가 데이터 격자의 셀을 두 번 클릭하면 새 창이 열리고 셀 내용이 해당 창에 자동으로 채워져 그렇게 할 수 있습니다. 편집 할 수 있습니다. 아무도 이것으로 나를 도울 수 있습니까? 감사.셀 내용을 새 창에 자동으로 채우는 것에 대한 도움말

+1

몇 가지 예제 코드를 보여주십시오. SO는 코드 용 사이트가 아닙니다. – Hogan

+0

전체 코드를 물어 보지 않고 시작할 수 있도록 도와줍니다. 자습서 등 .... –

+0

자세한 내용을 입력하십시오. 데이터 집합을 사용하여 데이터 집합을 채우고 있습니까? 데이터가 포함 된 밑줄이는 객체 모델이 있습니까? 자동으로 채워짐으로써 사용자가 코드를 입력하지 않고 올바른 필드를 채우거나 사용자 관점에서만 볼 수 있습니까? –

답변

0

이것을 처리하는 간단한 방법은 그리드의 dbl-click 이벤트에 직접 양식을 만들고 손으로 다양한 필드를 설정하고 표시하고 새 값을 가져오고 그리드를 업데이트하는 것입니다.

이 방법이 효과가 있지만 양식 이벤트 처리기로 직접 너무 많은 작업을하는 것은 좋지 않습니다. 양식에서 논리 및 도메인 모델을 분리 해보십시오. 이 당신에게 출발점을 제공 할 수 있습니다 그러나

... 이것은 PropertyGrid 잘 처리 할 수있는 일처럼 보인다

var form = new CellEditingForm(); 
form.Field1.Text = cellValue; 
form.ShowDialog(); 
string newValue = form.Field1.Text; 
// update the grid here... 
0

만 DataRow를 주어 편집 가능한 양식을 만드는 방법은 매우 원유 데모입니다. 그것은 Windows Forms를 사용하지만 어떤 프레임 워크를 사용하든 상관없이 DataRow를 가지고있을 가능성이 큽니다. 그렇지 않으면 외삽 수 있습니다.

이 내용은 일련의 컨트롤로 동적으로 양식을 만드는 방법을 보여줍니다. 그것은 사용자가 그것을 엉망으로 만든 후 데이터를 다시 읽을 수있는 근본적인 방법을 제공합니다.

사용자가 변경 한 데이터의 유효성을 검사하고 저장하는 방법에 대한 지침을 제공하지 않습니다. 양식에 DataRow를 첨부하고 TextBox에 바인딩을 사용하고 내장 된 ErrorProvider 기능을 사용하는 것에 대한 힌트를 제공합니다. 그렇게하면 행이 더러워지고 읽고 쓰는 데 사용하는 메커니즘 (예 : TableAdapter)이 정상적으로 처리됩니다.

당신이 사용하는 프레임 워크에 의존하기 때문에 모든 것을하지 않았습니다. 이것은 당신을 시작하게하는 간단한 예일뿐입니다. 여기서 어디로 가야 할 지에 대해 질문이 있으면 새롭고 구체적인 질문을하십시오.

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Diagnostics; 
using System.Drawing; 
using System.Windows.Forms; 

class DemoForm : Form 
{ 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     Application.Run(new DemoForm()); 
    } 

    public DemoForm() 
    { 
     DataTable dataTable = new DataTable { Columns = { "First", "Second", "Third" } }; 
     dataTable.Rows.Add("This", "Is", "Data"); 
     dataTable.Rows.Add("Some", "More", "Values"); 
     DataGridView dgv = new DataGridView 
     { 
      Dock = DockStyle.Fill, 
      DataSource = dataTable, 
      RowHeadersVisible = false, 
      SelectionMode = DataGridViewSelectionMode.FullRowSelect, 
      ReadOnly = true, 
     }; 
     dgv.DoubleClick += (s, e) => 
      { 
       if (dgv.SelectedRows.Count > 0) 
       { 
        DataRow dataRow = (dgv.SelectedRows[0].DataBoundItem as DataRowView).Row; 
        using (GenericDataRowForm form = new GenericDataRowForm(dataRow)) 
        { 
         if (form.ShowDialog(this) == DialogResult.OK) 
         { 
          // TODO: Validate and save data 

          // Just showing how to iterate GenericDataRowForm.Items 
          foreach (KeyValuePair<string, string> pair in form.Items) 
           Trace.WriteLine(String.Format("Column = {0}, Value = {1}", pair.Key, pair.Value)); 
         } 
        } 
       } 
      }; 
     Controls.Add(dgv); 
    } 
} 

class GenericDataRowForm : Form 
{ 
    public GenericDataRowForm() 
    { 
    } 
    public GenericDataRowForm(DataRow row) 
    { 
     // Basic dialog box styles 
     FormBorderStyle = FormBorderStyle.FixedDialog; 
     MinimizeBox = MaximizeBox = ShowInTaskbar = false; 
     StartPosition = FormStartPosition.CenterParent; 

     // You would probably want to set the caption (this.Text) to 
     // something meaningful from the outside, so left it out here. 

     // Record the number of items 
     itemCount = row.Table.Columns.Count; 

     // Create a TableLayoutPanel to arrange the Label/TextBox pairs (and the Ok/Cancel buttons). 
     TableLayoutPanel panel = new TableLayoutPanel 
     { 
      Name = "LayoutPanel", 
      ColumnCount = 2, 
      ColumnStyles = { new ColumnStyle(), new ColumnStyle(SizeType.Percent, 100F) }, 
      RowCount = itemCount + 1, 
      // We will dock it later, but we want to know how big it should be. 
      AutoSize = true, 
     }; 

     int itemIndex = 0; // Intentionally declared outside as we'll use it for the buttons below. 
     for (; itemIndex < itemCount; itemIndex++) 
     { 
      panel.RowStyles.Add(new RowStyle()); 
      string columnName = row.Table.Columns[itemIndex].ColumnName; 
      panel.Controls.Add(new Label { Text = columnName, AutoSize = true, Anchor = AnchorStyles.Right }, 0, itemIndex); 
      // Note that the text box has its Name set to the data column name and it's Text to the value of that column. 
      panel.Controls.Add(new TextBox { Name = columnName, Text = row[itemIndex].ToString(), Dock = DockStyle.Fill }, 1, itemIndex); 
     } 

     // Add Ok and Cancel buttons 
     panel.RowStyles.Add(new RowStyle()); 
     panel.Controls.Add(new Button { Text = "Ok", Name = "OkButton", DialogResult = DialogResult.OK }, 0, itemIndex); 
     panel.Controls.Add(new Button { Text = "Cancel", Name = "CancelButton", DialogResult = DialogResult.Cancel }, 1, itemIndex); 
     AcceptButton = panel.Controls["OkButton"] as IButtonControl; 
     CancelButton = panel.Controls["CancelButton"] as IButtonControl; 

     // Adjust this Form's size to the panel. 
     ClientSize = new Size(320, panel.Height + 10); 
     // Then dock the panel so that it conforms to the Form. 
     panel.Dock = DockStyle.Fill; 

     Controls.Add(panel); 
    } 

    public int ItemCount 
    { 
     get { return itemCount; } 
    } 

    // We need some way for the outside world to view the data that 
    // might have been edited by the user. This could be much more 
    // complicated. As a simple example, this allows the consumer 
    // to iterate over each item as a KeyValuePair. The key is the 
    // data column name and the value is the Text field of the TextBox. 
    public IEnumerable<KeyValuePair<string, string>> Items 
    { 
     get 
     { 
      if (itemCount > 0) 
      { 
       TableLayoutPanel panel = Controls["LayoutPanel"] as TableLayoutPanel; 
       foreach (Control control in panel.Controls) 
       { 
        TextBox textBox = control as TextBox; 
        if (textBox != null) 
         yield return new KeyValuePair<string, string>(textBox.Name, textBox.Text); 
       } 
      } 
     } 
    } 

    private int itemCount = 0; 
} 
관련 문제