如何从另一个表单更新datagridview
本文关键字:更新 datagridview 表单 另一个 | 更新日期: 2023-09-27 18:10:03
我有两种形式:ProductSelectionForm
和QuantityPriceForm
ProductSelection
表单包含一个3列的datagridview (
- 产品名称
- 价格
我从getQuantityPrice
表单中取出Quantity
和price
,其中包含2个文本框用于上述值。
Productselection Form
:
public void getQuanPrice() // call getQuantityPrice form
{
QuantityPriceForm obj = new QuantityPriceForm(this);
obj.ShowDialog();
}
getQuantityPrice Form
:
ProductSelection form1; // public initialization
public QuantityPriceForm(ProductSelection form_1)
{
InitializeComponent();
form1 = form_1;
}
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.Yes)
{
form1.dgvProducts.CurrentRow.Cells[2].Value = quant;
form1.dgvProducts.CurrentRow.Cells[3].Value = agreePrice;
this.Close();
}
}
数据网格视图不更新表单1中的数量和价格列。我做错了什么?
机会是,您的产品选择表单仍然有DataGridView控件dgvProducts
设置为Private(默认)。
你可以将它设置为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 Form中,您需要创建这两个公共属性:
// 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();
}
}