所以我有一類用于評分系統的公共變數,但似乎無法找到任何簡單的方法將它們全部列印到表中的不同列。
該類的代碼如下,你可以看到它只是一個公共陣列的負載。
{
public static string[] playerName = new string[9];
public static int[] playerTotalScore = new int[9];
public static int[] playerEventScore = new int[9];
}
我希望它以表格的形式輸出,第一列顯示名稱,第二列顯示總分。我怎樣才能讓它做到這一點?因為我似乎找不到適合我的用例的任何解決方案
uj5u.com熱心網友回復:
試試這個方法:
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public long TotalScore { get; set; }
public long EventScore { get; set; }
}
保存:
Player player= new Player();
player.Name="player_name";
player.TotalScore =1200;
player.EventScore =123;
List<Player> players= new List<Player>();
players.add(player);
uj5u.com熱心網友回復:
你可以看到它只是一堆公共陣列。
與 masoud 的回答一樣,我想指出我們不在面向物件語言中這樣做:
//data store for 10 people
public string[] Names = new string[10];
public int[] Scores = new int[10];
public DateTime[] Birthdays = new DateTime[10];
我們沒有為姓名宣告 10 個陣列,為分數宣告 10 個陣列,為生日宣告 10 個陣列,然后有一個“相同位置的資料來自同一個人:
Names[0] = "John";
Scores[0] = 99;
Birthdays[0] = new DateTime(1970,1,1);
當我們想要將資料保存在一起時,我們創建一個表示它的類:
public class Person{
public string Name {get;set;}
public int Score {get;set;}
public DateTime Birthday {get;set;}
}
然后我們就可以有10個陣列的,如果你想...
var people = new Person[10];
順便說一下,在現代 C# 中,我們可以使用records 來快速宣告保存資料的類。它們還有一些其他功能,使它們對于存盤在字典中并相互比較等有用:
public record Person(string Name, int Score, DateTime Birthday) //roughly the same as above
所以現在您對這個概念感到失望,您可以快速輕松地填充 DataGridView .. DataTables 的快速介紹:
DataTable 是 DataRow 的集合。它還有一個 DataColumn 的集合。像 DataGridview 這樣的控制元件將使用 DataColumns 來知道要繪制多少列以及使用行數。DataTable就像上面的Person[10],每個DataRow就像一個單獨的Person
var dt = new DataTable();
dt.Columns.Add("Name"); //string, by default
dt.Columns.Add("Score", typeof(int));
dt.Columns.Add("Birthday", typeof(DateTime));
然后用資料填充行:
dt.Rows.Add("John", 90, new DateTime(1970,1,1));
dt.Rows.Add("Sarah", 78, new DateTime(1970,1,2));
dt.Rows.Add("Jane", 99, new DateTime(1970,1,3));
然后告訴 DataGridView 將其用作資料源:
peopleDataGridView.DataSource = dt;
DataGridView 也可以使用,例如 a List<Person>,因此您可以:
var ps = new List<Person>();
ps.Add(new Person{Name = "John", Score = 90, Birthday = DateTime.Now});
peopleDataGridView.DataSource = ps;
不過,您可能需要搖晃這些柱子;Columns如果使用資料表,DGV 將按照集合的順序創建列,但它可能不會按照與 Person 源代碼中出現的屬性相同的順序創建列
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403408.html
標籤:
下一篇:如何用兩個逗號分割字串,,?
