![](/img/trans.png)
[英]Pass data from one form to a specific cell in a datagridview from another form in C#
[英]How can I pass multiple cell values of datagridview from one form to another at same time in C#?
我是C#的新手,正在使用Windows窗體。 我有帶有datagridview
Form1
和帶有地圖的Form2
。
我想同時將來自Form1
未知數量(無限數量)的datagridview
單元格值傳遞給form2
,這是因為我想將所選的form1
單元格值(地址)顯示在地圖上的form2
。 我知道如何使用setter和getter,但在這種情況下,我認為setter和getter將無法工作,因為我想傳遞給form2
的像元值的數量是未知的。
有誰知道我如何同時將多個datagridview
單元格值從form1
傳遞到form2
? 請幫忙,謝謝
Form1中的這段代碼循環遍歷所有選定的行,我想將Cells[0].Value
傳遞給form2
:
foreach (DataGridViewRow row in DGV.SelectedRows)
{
// here I have to pass all selected row.Cells[0].Value to form2
}
列出字符串並將其傳遞到下一個表單
List<string> cellvalueList = new List<string>();
foreach (DataGridViewRow row in DGV.SelectedRows)
{
// here I have to pass all selected row.Cells[0].Value to form2
cellvalueList.Add(row.Cells[0].Value);
}
現在,當您調用下一個表單時,您需要一個在此處接受List的屬性(或通過構造函數傳遞)。 像這樣
Form2 newForm = new Form();
newform.Values = cellvalueList; // this Values is the List<string> property in Form2
newForm.Show();
如果您的form2已經可見,則可以傳遞完整的列表
newform.SetValues(cellvalueList);
此SetValues是Form2中的函數,該函數將字符串列表作為參數
這是我的解決方案:
List<string> values = new List<string>();
foreach (DataGridViewRow row in DGV.SelectedRows)
{
values.Add(row.Cells[0].Value);
}
myForm2.SetForm1Values(values);
這里有一些警告,首先是您必須能夠引用其他表單的實例(在此表示為myForm2
)。 我在這里使用了一種稱為SetForm1Values
的方法,因為您表示不確定是否可以使用屬性,但實際上,屬性設置器將與該方法一樣有效。
您可以使用以下代碼獲取所選行的Cells[0]
的值:
List<string> selectedData = this.dataGridView1.SelectedRows.Cast<DataGridViewRow>()
.Select(row => (string)row.Cells[0].Value)
.ToList();
等效於:
List<string> selectedData = new List<string>();
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
{
selectedData.Add((string)row.Cells[0].Value);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.