C# 如何从其他表单更新datagridview?

C# 如何从其他表单更新datagridview?,c#,winforms,datagridview,C#,Winforms,Datagridview,我有两个表单:ProductSelectionForm和QuantityPriceForm ProductSelection表单包含一个具有3列的datagridview 品名 量 价格 我从getQuantityPrice表单中获取数量和价格,该表单包含两个文本框用于上述值 到目前为止,我一直致力于此代码: 产品选择表: public void getQuanPrice() // call getQuantityPrice form { QuantityPriceForm obj

我有两个表单:ProductSelectionForm和QuantityPriceForm

ProductSelection表单包含一个具有3列的datagridview

品名 量 价格 我从getQuantityPrice表单中获取数量和价格,该表单包含两个文本框用于上述值

到目前为止,我一直致力于此代码:

产品选择表:

 public void getQuanPrice() // call getQuantityPrice form
 {
    QuantityPriceForm obj = new QuantityPriceForm(this);
    obj.quant = (int)dgvProducts.CurrentRow.Cells[2].Value;
    obj.agreePrice = (double)dgvProducts.CurrentRow.Cells[3].Value;
    if (obj.ShowDialog() == DialogResult.OK)
    {
      dgvProducts.CurrentRow.Cells[2].Value = obj.quant;
      dgvProducts.CurrentRow.Cells[3].Value = obj.agreePrice;
    }
 }
getQuantityPrice表格:


数据网格视图不会更新表格1中的数量和价格列。我做错了什么?

很可能,您的产品选择表单仍将DataGridView控件DGVPProducts设置为默认的私有

您可以将其设置为public,以便您的子窗体可以访问它,但这是一种糟糕的样式

相反,将参数传递给您的子窗体,并在成功时重新读取它们:

产品选择表:

 public void getQuanPrice() // call getQuantityPrice form
 {
    QuantityPriceForm obj = new QuantityPriceForm(this);
    obj.quant = (int)dgvProducts.CurrentRow.Cells[2].Value;
    obj.agreePrice = (double)dgvProducts.CurrentRow.Cells[3].Value;
    if (obj.ShowDialog() == DialogResult.OK)
    {
      dgvProducts.CurrentRow.Cells[2].Value = obj.quant;
      dgvProducts.CurrentRow.Cells[3].Value = obj.agreePrice;
    }
 }
现在,在getQuantityPrice表单上,您需要创建这两个公共属性:

// ProductSelection form1; (you don't need this)

public QuantityPriceForm()
{
  InitializeComponent();
}

public int quant {
  get { return (int)txtQuantity.Text; }
  set { txtQuantity.Text = value.ToString(); }
}

public int agreePrice {
  get { return (double)txtAgreePrice.Text; }
  set { txtAgreePrice.Text = value.ToString(); }
}

private void button1_Click(object sender, EventArgs e)
{
  DialogResult saveData = MessageBox.Show("Do you want to save the data?",
    "Save Data",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question);

  if (saveData == DialogResult.OK)
  {
    this.DialogResult = saveData;
    this.Close();
  }
}

@Codexer先生,是我还是他事实上,他可能在上课,这是他的家庭作业。
// ProductSelection form1; (you don't need this)

public QuantityPriceForm()
{
  InitializeComponent();
}

public int quant {
  get { return (int)txtQuantity.Text; }
  set { txtQuantity.Text = value.ToString(); }
}

public int agreePrice {
  get { return (double)txtAgreePrice.Text; }
  set { txtAgreePrice.Text = value.ToString(); }
}

private void button1_Click(object sender, EventArgs e)
{
  DialogResult saveData = MessageBox.Show("Do you want to save the data?",
    "Save Data",
    MessageBoxButtons.YesNo,
    MessageBoxIcon.Question);

  if (saveData == DialogResult.OK)
  {
    this.DialogResult = saveData;
    this.Close();
  }
}