我正在尝试制作一个小程序来获取用户输入并将其存储在文件中,但我希望该文件最多包含 100 个元素:
假设用户添加了 100 个名称,用户添加的下一个名称将显示一条消息“列表已满”
这是我到目前为止所做的代码:
public Form1()
{
InitializeComponent();
}
private string SongName, ArtistName;
public void Registry()
{
List<Name> MusicList = new List<Name>(); //Create a List
MusicList.Add(new Name(SongName = txtSongName.Text, ArtistName = txtArtistName.Text)); //Add new elements to the NameClass
//check if the input is correct
if (txtSongName.TextLength < 1 || txtArtistName.TextLength < 1)
{
Info info = new Info();
info.Show();
}
else //if input is correct data will be stored
{
//Create a file to store data
StreamWriter FileSaving = new StreamWriter("MusicList", true);
for (int i = 0; i < MusicList.Count; i++)
{
string sName = MusicList[i].songName; //Create new variable to hold the name
string aName = MusicList[i].artistName; //Create new variable to hold the name
FileSaving.Write(sName + " by "); //Add SongName to the save file
FileSaving.WriteLine(aName); //Add ArtistName to the save file
}
FileSaving.Close();
}
}
private void btnEnter_Click(object sender, EventArgs e)
{
Registry();
//Set the textbox to empty so the user can enter new data
txtArtistName.Text = "";
txtSongName.Text = "";
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}