C#为不同目的使用相同的winform(新手)

C#为不同目的使用相同的winform(新手),c#,winforms,datagridview,C#,Winforms,Datagridview,我是c#和winforms的新手,我的想法是创建一个简单的应用程序,其中包含像图中这样的Form1 在dategridview中,我可以显示来自数据库表产品的数据(ID不可见),然后当我单击按钮New时,Form2将打开 当我想编辑某些项目时,我想使用相同的Form2,在datagridview中选择特定的行,然后单击按钮edit(我已经在两个不同的win表单上做到了这一点)。我如何实现这一点? 这就是我到目前为止所做的: 纽扣 private void toolStripButton1_C

我是c#和winforms的新手,我的想法是创建一个简单的应用程序,其中包含像图中这样的Form1

在dategridview中,我可以显示来自数据库表产品的数据(ID不可见),然后当我单击按钮New时,Form2将打开

当我想编辑某些项目时,我想使用相同的Form2,在datagridview中选择特定的行,然后单击按钮edit(我已经在两个不同的win表单上做到了这一点)。我如何实现这一点? 这就是我到目前为止所做的:

纽扣

private void toolStripButton1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2(this);
        f2.Show();
    }
方法PerformRefresh()

表格2

然后,对于表单1上的按钮编辑,我创建了类MyProducts,并创建了这个类的对象,我想将其传递给表单2

MyProducts myProducts = new MyProducts();
        myProducts.ID = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
        myProducts.Name = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        myProducts.Quantity = Int32.Parse(dataGridView1.CurrentRow.Cells[2].Value.ToString());
现在我想显示Form2,单击编辑按钮,当显示Form2时,我想将所选项目属性显示在两个文本框控件中。 有什么想法吗?
提前感谢。

将MyProducts的公共属性提供给Form2,并填写文本框

private MyProducts product;
public MyProducts Product
{
  set
  {
    product = value;
    if (product != null)
    {
      nameTextBox.Text = product.Name;
      quantityTextBox.Text = product.Quantity.ToString();
    }
}
然后在打开表单进行编辑之前,传递要编辑的MyProducts元素

private void toolStripButton2_Click(object sender, EventArgs e)
{
    MyProducts myProducts = new MyProducts();
    myProducts.ID = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
    myProducts.Name = dataGridView1.CurrentRow.Cells[1].Value.ToString();
    myProducts.Quantity = Int32.Parse(dataGridView1.CurrentRow.Cells[2].Value.ToString());
    Form2 f2 = new Form2(this);
    f2.Product = myProducts;
    f2.Show();
}
然后安全检查产品是否有价值,以确定更新或插入

private void toolStripButton1_Click(object sender, EventArgs e)
{
    string Name = textBox1.Text;
    int Quantity = Int32.Parse(textBox2.Text);
    if (product != null)
    {
      //SQL Update command
    }
    else
    {
      //SQL Insert command
    }

    //SQL Execute
}
希望这有帮助

private void toolStripButton2_Click(object sender, EventArgs e)
{
    MyProducts myProducts = new MyProducts();
    myProducts.ID = Int32.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
    myProducts.Name = dataGridView1.CurrentRow.Cells[1].Value.ToString();
    myProducts.Quantity = Int32.Parse(dataGridView1.CurrentRow.Cells[2].Value.ToString());
    Form2 f2 = new Form2(this);
    f2.Product = myProducts;
    f2.Show();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
    string Name = textBox1.Text;
    int Quantity = Int32.Parse(textBox2.Text);
    if (product != null)
    {
      //SQL Update command
    }
    else
    {
      //SQL Insert command
    }

    //SQL Execute
}