将一个表单上的DataGridView中的数据显示到另一个表单上的TextBoxes中



我有两个表单。ShoppingBasketForm.csEditBasketPopup.cs .

ShoppingBasketForm.csDataGridView中显示一个购物篮,称为dataGridBasket,它绑定到来自我的OrderItem类的单独List<OrderItem>OrderItems。这可以通过在Product Name QuantityLatestPrice页面上填写提供的文本框/数字upicdown来添加,然后单击Add按钮btnAdd。它还可以通过单击Remove按钮btnRemove从所选行中删除数据。

我现在试图实现一个Edit按钮btnEdit,一旦点击,它实例化EditBasketPopup的形式。在这个表单上有三个文本框/数字上下显示再次ProductName QuantityLatestPrice

我如何从dataGridBasket上的选定行获取数据(用户不能选择单个单元格),并在用户激活btnEdit单击事件时使用它来填充三个文本框?

我尝试在EditBasketPopup.cs中创建一个属性来保存第一种形式的数据,但不确定如何以字符串形式从dataGridBasket中选定的行中提取数据,并且还遇到了需要从行中每个单元格中获取单个数据的问题,因为它们被绑定到不同的属性。

对于这个问题,我显然没有太多的示例代码,因为它是关于如何而不是为什么的理论,但如果你需要任何东西,请告诉我。

@Harry Sweetman ok首先要获取你的datagridview的选定元素,你可以这样做:

 //recover the view row
 DataGridViewRow drv = (DataGridViewRow)dataGridBasket.Current;
 //if the row is not empty => basket was selected in the dataGridView
 if (drv.Cells[0].Value != null)
 {
      //Here we get the first cell selected let say the name is like the id:
      string idBasketToEdit = drv.Cells[0].Value.ToString().Clone().ToString();
      //Now we instantiate the form EditBasketPopoup, but sending the selected basket as a parameter                  
       frmEdit = new EditBasketPopoup(idBasketToEdit);
       frmEdicion.Name = "Edit basket";
       frmEdicion.ShowDialog();         
 }

还需要在EditBasketPopup.cs中有一个带有Basket参数的表单构造函数,如下所示:

    public EditBasketPopup(string idBasket)
    {
        InitializeComponent();
        Basket b = control.GetBasket(idBasket);
        //You set the form boxes:
        txtProductName.Text = b.ProductName;
        txtLatestPrice.Text = b.LatestPrice;
        txtQuantity.Text = b.Quantity;
    }

最后让我们假设你有一个控制器(例如,BasketController),你有一些逻辑。这里假设你搜索你想要编辑的篮子上的集合,它绑定你的datagridview (dataGridBasket)。

public Basket GetBasket(string idBasket)
{
    try
    {
        //basketCollection is the one that you use to bind dataGridBasket
        return basketCollection.Find(x => x.idBasket.Equals(idBasket));
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

最新更新