[英]Displaying List of Objects on a DataGridView / ListView
我在一個類中有一個 List,它從 .txt 文件加載數據,然后將數據存儲在位於另一個包含構造函數和所有類的對象中。 在我的表單中,我需要在 DataGridView/ListView 中顯示所有數據,以便我可以查看它,在需要時選擇並進行更改。
但是,當我在表單上執行此操作時,沒有任何效果,或者它只會在頂部顯示構造函數名稱,但不填充任何數據。 我已經用盡了所有選項,用谷歌搜索了左右和中心,似乎沒有任何方法有效。 嘗試過諸如 DataSource = <"class">.theList 之類的東西。 甚至嘗試過 DataBindings 等,但似乎沒有任何效果。 它給出了一個類似於<"class">.theList 不能像方法一樣使用的錯誤
呼吁 Stack OverFlow 的偉大人物幫助我朝着正確的方向前進。 謝謝大家!
編輯我已經粘貼了一些示例代碼,有關它的任何問題請提出。 謝謝你們。
public class Form{
private void form_Load()
{
Wrapper wrap = new Wrapper();
List<Child> tempList = new List<Child>();
tempList = wrap.cList;
dataGridView1.DataSource = tempList;
}
}
class Wrapper{
public List<Child> cList = new List<Child>();
public void LoadPerson()
{
string filePath = @"filepath";
//StreamReader
//code to Add each different person + their details into the
protected fields
//stores in cList variables which are in Adult
}
}
class Adult{
protected string username, firstName;
protected int number;
}
class Child: Adult{
public Child(string Username, string Password, int Number)
{
username = Username;
password = Password;
number = Number;
}
//public getters/setters next
}
如果沒有看到您的代碼,就很難看出問題是什么!
但是如果您想查看對象,我想建議另一種方法,那么 ObjectListView 是一種替代解決方案。
http://objectlistview.sourceforge.net/cs/index.html
它是一個列表視圖而不是一個數據網格視圖,但您可以簡單地將您的對象的集合傳遞給它,它就會顯示給您。
它也非常強大,允許您自定義很多東西。
沒有代碼和數據樣本,很難給出好的建議。
我將按照以下方式從您擁有的數據中創建一個 DataTable(根據您構建的數據結構,代碼需要 mod):
VB.NET:
Dim dt as New Datatable
dt.Columns.Add("ID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
For ir = 0 to <SRC>.rows.count -1 ' modify to which ever way you can go through your data
dt.Rows.Add(<SRC>("ID"), <SRC>("name"))
Next
Me.DataGridView1.datasource = dt
C#:
Datatable dt = new Datatable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
for (ir = 0; ir <= <SRC>.rows.count - 1; ir++) {
// modify to which ever way you can go through your data
dt.Rows.Add(<SRC>("ID"), <SRC>("name"));
}
this.DataGridView1.datasource = dt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.