C#を使用してクイズを作成しました(楽しいと覚えてください) 私の最高得点グリッドには、playerdetailsクラスの情報1回ではなく同じプレイヤーで5回表示されます。コードを参照してください:C#でテキストファイルに書き込むが、グリッドに表示されているときに同じ情報が繰り返される
public frmHighscore()
{
InitializeComponent();
//Only save the test scores once
if (!File.Exists("highscores.txt"))
{
SaveScores();
}
LoadScores();
//Sort the grid based on the value of Column 1 which will be the score value
dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Descending);
}
private void SaveScores()
{
//Open filestram and streamwriter needed to save details to a text file
FileStream fileStream = new FileStream("highscores.txt", FileMode.Append, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
try
{
//loop over each player
{
//Write details of the player to the textfile in format playerName~Score
foreach (Player player in PlayerList)
{
streamWriter.WriteLine(player.playerName + "~" + player.playerScore);
}
}
}
catch (Exception)
{
MessageBox.Show("Error loading the scores", "Please try again");
}
finally
{
//close streamwriter and filestream
streamWriter.Close();
fileStream.Close();
}
}
private void LoadScores()
{
//Check if the file exists
if (File.Exists("highscores.txt"))
{
//Read in all the details of the text file
var playerScores = File.ReadAllLines("highscores.txt");
//check if players exist in the text file
if (playerScores.Length > 0)
{
//Loop over each player details
foreach (var playerScore in playerScores)
{
//Add the player name and score to the datagrid
var splitDetails = playerScore.Split('~');
dataGridView1.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[1]));
}
}
else
{
//Hide the grid and show the No Scores label
HideGrid();
}
}
マイプレイヤークラスは次のようになります。player
変数は、私はそれが、その後
streamWriter.WriteLine(PlayerDetails.playerName + "~" + PlayerDetails.playerScore);
であると仮定するものであれば 名前空間CWQuiz
{
public class Player
{
public string Username;
public int Score;
public int quizNumber;
public string playerName { get; set; }
public int playerScore { get; set; }
public static List<Player> player = new List<Player>();
public Player(string name)
{
Username = name;
Score = 0;
}
}
}
foreach(PlayerDetailsのvarプレーヤー) streamWriter.WriteLine(player .playerName + "〜" player .playerScore); } –
どのようなタイプが 'PlayerDetails.playerName'ですか? –
OP37 PlayerDetails.playerNameのコメントによると、文字列型 –