簡體   English   中英

C#從其他形式填充dataGrid

[英]C# filling dataGrid from other form

我想將數據從我填寫的表單中添加到另一個包含DataGridView的表單中。 問題在於他們彼此看不見。 我嘗試制作這些數據字段(文本框和組合框)的結構,並制作一個靜態列表,希望以其他形式與表格一起使用。 但是它仍然不起作用。 我有一個表格雕像和一個表格表格。 我試過了

foreach('struct i made in both forms' rs in 'Statue.that static list')
{
-fill table-
} 

但是顯示錯誤“無法將Statue.registeStruct類型轉換為Table.registreStruct”。 你能幫我嗎? 謝謝

使用鼠標在Visual Studio中選擇您的組件(我的意思是dataGrid)。 然后轉到屬性列表,並將“修飾符”行從私有更改為公共。 不是,您可以從其他表單訪問該dataGrid。

假設您使用的是Windows Forms

您想使用DataBinding

我堅決建議您每個DataGridView都有一個BindingSource ,然后公開其DataSource屬性,以便在兩者之間共享相同的源。

public class Form1 : Form {
    public IList<MyObjectType> DataContext {
        get { return (IList<MyObjectType>)myBindingSource.DataSource; }
        set { myBindingSource.DataSource = value; }
    }
}

public class Form2 : Form {
    public IList<MyObjectType> DataContext {
        get { return (IList<MyObjectType>)myBindingSource.DataSource; }
        set { myBindingSource.DataSource = value; }
    }
}

然后,以另一種形式,您將能夠在兩者之間共享信息。

public class Form3 : Form {
    private void onWhateverEventItMIghtBe(object sender, EventArgs e) {
        instanceOfForm2.DataContext = instnceOfForm1.DataContext;
    }
}

您確實需要在設計器模式下設置數據綁定。

使用向導將PropertyWindow中的BindingSource.DataSource屬性設置為新的DataSource ,以便兩個DataGridView均可將其列設置為所需的列。 然后,將您的DataGridView.DataSource屬性設置為BindingSource

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM