我需要能够将数据存储在数组中以显示在列表框中,到目前为止,我只能得到文本文件的第一个单词(名称)。
我一直在使用Line Split方法,尽管这会将所有部分拆分为自己的行,但是执行此方法也会带来“索引超出数组范围”的问题。请帮忙,我已经整整呆了2天了。
// - - - - - - - Selection Screen - - - - - - -
public SelectionScreen()
{
InitializeComponent();
//Loading from text file.
string[] PrimaryArray = new string[12];
PrimaryArray = System.IO.File.ReadAllLines(@"Test1.txt");
foreach (string line in PrimaryArray)
{
string[] Parts = line.Split(',');
CharStats temp = new CharStats();
temp.Name = Parts[0];
temp.Description = Parts[1];
temp.Notes = Parts[2];
temp.MaxHP = Convert.ToInt16(Parts[3]);
temp.MaxMP = Convert.ToInt32(Parts[4]);
temp.Atk = Convert.ToInt32(Parts[5]);
temp.Def = Convert.ToInt32(Parts[6]);
temp.Mat = Convert.ToInt32(Parts[7]);
temp.Mdf = Convert.ToInt32(Parts[8]);
temp.Agi = Convert.ToInt16(Parts[9]);
temp.Luk = Convert.ToInt16(Parts[10]);
temp.Lvl = Convert.ToInt16(Parts[11]);
ListboxCharacterList.Items.Add(temp.Name);
}
}
// - - - - - - - Writing stats - - - - - - -
public string WriteStats()
{
return Environment.NewLine + Name + "," + Description + "," + Notes + "," +
MaxHP + "," + MaxMP + "," + Atk + "," + Def + "," + Mat + "," +
Mdf + "," + Agi + "," + Luk + "," + Lvl;
}
// - - - - - - - TextFile - - - - - - -
//Mike,Desc.,Notes,1000,500,6,7,3,2,6,9
答案 0 :(得分:0)
ListBox
可以包含任何class
的任何实例。您可以将CharStats
添加到其中。您只需要覆盖ToString()
即可执行该操作以在框中显示值。如果要选择SelectedItem
,则必须将其强制转换为CharStats
。
使用CsvHelper
(NuGet
软件包)可以轻松读取Csv文件。例如:
public class CharStats
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return this.FirstName + " " + this.LastName;
}
}
public Form1()
{
InitializeComponent();
// From File:
// FirstName;LastName;Age
// d;D;4
// e;E;5
using (StreamReader sr = new StreamReader(@"C:\Temp\myfile.csv"))
{
using (CsvHelper.CsvReader csvReader = new CsvHelper.CsvReader(sr))
{
IEnumerable<CharStats> statList = csvReader.GetRecords(typeof(CharStats)).Cast<CharStats>();
foreach (CharStats cs in statList)
{
this.listBox1.Items.Add(cs);
}
}
}
this.listBox1.Items.Add(new CharStats() { FirstName = "a", LastName = "A", Age = 1 });
this.listBox1.Items.Add(new CharStats() { FirstName = "b", LastName = "B", Age = 2 });
this.listBox1.Items.Add(new CharStats() { FirstName = "c", LastName = "C", Age = 3 });
this.listBox1.SelectedIndex = 1;
var item = this.listBox1.SelectedItem;
CharStats selected = item as CharStats;
if (selected != null)
MessageBox.Show("Worked. We selected: " + selected.FirstName + " " + selected.LastName + " (" + selected.Age + ")");
}
这将显示一个这样的ListBox:
a A
b B
抄送
然后选择的将是正确的对象。 MessageBox
将显示
b B(2)