我有2个表单,Form1包含datagridview和按钮“add”,Form2包含文本框和按钮“save”,
我想添加行,并在单击添加按钮时出现form2,然后在单击“保存”按钮时在datagridview中保存form2中的信息 这是我用于添加和保存按钮的代码,但是当我这样做时,它只保存从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 :(得分: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
}
}
这不是最好的方法,但这个方向可能更容易尝试... 希望它有所帮助