[英]Displaying data from a DataGridView on one Form into TextBoxes on another
我有兩種形式。 ShoppingBasketForm.cs
和EditBasketPopup.cs
。
ShoppingBasketForm.cs
在名為dataGridBasket
的DataGridView
顯示一個購物籃,該購物籃綁定到來自我的OrderItem
類的單獨的List<OrderItem>OrderItems
。 可以通過在“ Product Name
Quantity
和“ LatestPrice
”頁面上填寫提供的文本框/ numericUpDowns,然后單擊“ Add
按鈕btnAdd
來Add
。 通過單擊“ Remove
按鈕btnRemove
它也可以從所選行中刪除數據。
我現在正在嘗試實現一個btnEdit
Edit
按鈕,單擊該按鈕將實例化EditBasketPopup
表單。 在此表單上,將再次顯示三個文本框/數字下標ProductName
Quantity
和LatestPrice
。
我如何從dataGridBasket
上的選定行中獲取數據(用戶無法選擇單個單元格),並在用戶激活btnEdit
click事件時使用它填充三個文本框?
我嘗試在EditBasketPopup.cs
創建一個屬性來保存第一個表單中的數據,但是不確定如何從dataGridBasket
中的選定行中以字符串形式提取數據,並且還遇到了需要從每個表單中獲取單獨數據的問題該行中的單元格,因為它們綁定到不同的屬性。
對於這個問題,我顯然沒有太多示例代碼,因為這是關於如何而不是為什么的理論,但是如果您需要任何信息,請告訴我。
@Harry Sweetman好吧,首先獲取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)的集合中搜索要編輯的Basket。
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.