2016-12-13 154 views
0

我有2种形式添加行,Form1包含在DataGridView和按钮“添加”,Form2包含textboxs和按钮“保存”,C#从另一种形式

我要添加行,当添加按钮是出现窗口2点击,然后保存信息从form2在datagridview点击保存按钮时 这是我用于添加和保存按钮的代码,但是当我这样做时,它只保存从form1写入的信息(保存按钮没有如果不更新datagridview的话)

private void AddButton_Click(object sender, EventArgs e) 
{ 
    Form2 windowAdd = new Form2(); 
    windowAdd.SetDesktopLocation(this.Location.X + this.Size.Width, this.Location.Y); 
    windowAdd.ShowDialog(); 
    var frm2 = new Form2(); 
    frm2.AddGridViewRows(textName.Text, textDescription.Text, textLocation.Text, textAction.Text); 
    textName.Focus(); 
    this.stockData.Product.AddProductRow(this.stockData.Product.NewProductRow()); 
    productBindingSource.MoveLast();  
} 

private void SaveButton_Click(object sender, EventArgs e) 
{ 
    productBindingSource.EndEdit(); 
    productTableAdapter.Update(this.stockData.Product); 
    this.Close(); 
} 
+0

你的Add按钮的代码似乎启动窗口2的对话框(windowAdd) (你使用ShowDialog来显示它的Modal,所以用户必须关闭窗体才能继续移动,窗体将是空白的),然后你用Form1的Textboxes中的值显式地创建另一个form2(frm2)来调用看起来静态的AddGridViewRows方法。然后,将Focus设置为Form1.textName,然后向产品添加一行,并在数据源中添加MoveLast。这里有太多错误,很难知道从哪里开始。 –

回答

0

试试这个方法。 Form2可以接受一些建设参数。您将必须解析对productBindingSource和productDataAdaptor的引用。

public partial class Form2 : Form 
{ 
    private DataRow _theRow; 
    private bool _isNew; 

    public Form2(DataRow theRow, bool isNew) 
    { 
     InitializeComponent(); 
     _theRow = theRow; 
     _isNew = isNew; 
    } 

    private void Form2_Load(object sender, EventArgs e) 
    { 
     textName.Text = _theRow["Name"]; 
     // Etc 
    } 

    private void btnSave_Click(object sender, EventArgs e) 
    { 
     // This is your add/edit record save button 
     // Here you would do stuff with your textbox values on form2 
     // including validation 
     if (!ValidateChildren()) return; 
     if (_isNew) 
     { 
      // Adding a record 
      productBindingSource.EndEdit(); 
      productTableAdapter.Update(); 
     } 
     else 
     { 
      // Editing a record 
     } 
     this.Close(); 
    } 
} 

这改变了您在Form1.Add Button事件中的呼叫。下面展示了如何利用使用块来显示表单。

private void btnAdd_Click(object sender, EventArgs e) 
    { 
     DataRow newRow = stockData.Product.NewProductRow(); 
     using (var addForm = new Form2(newRow, true)) 
     { 
      addForm.StartPosition = FormStartPosition.CenterParent; 

      addForm.ShowDialog(this); 
      // Here you could access any public method in Form2 
      // You could check addForm.DialogResult for the status 
     } 

    } 

这不是做到这一点的最好办法,但这个方向可能是尝试一种更简单的方法... 希望它可以帮助