我希望每当用户单击"添加人员"按钮时,personID都会增加,但每次再次运行时,增量又从1开始。此外,列名总是显示在用户的每次输入中,我只希望它在csv文件中显示一次。
我只是一个学生,刚开始接触C#。
Person.cs
namespace WPFApp
{
public class Person
{
[CsvColumn(Name = "Person ID", FieldIndex = 1)]
public string? personID { get; set; }
[CsvColumn(Name = "Last Name", FieldIndex = 2)]
public string? LastName { get; set; }
[CsvColumn(Name = "First Name", FieldIndex = 3)]
public string? FirstName { get; set; }
[CsvColumn(Name = "Middle Name", FieldIndex = 4)]
public string? MiddleName { get; set; }
}
}
AddPerson.xaml.cs
namespace WPFApp
{
/// <summary>
/// Interaction logic for AddPerson.xaml
/// </summary>
public partial class AddPerson : Page
{
int personID = 0;
public AddPerson()
{
InitializeComponent();
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
personID++;
var personList = new List<Person>()
{
new Person{ personID = personID.ToString(), LastName = LastNameBox.Text, FirstName = FirstNameBox.Text, MiddleName = MiddleNameBox.Text}
};
var csvFileDescription = new CsvFileDescription
{
FirstLineHasColumnNames = true,
SeparatorChar = ','
};
var csvContext = new CsvContext();
using (TextWriter writer = new StreamWriter("PersonFIles.csv", true))
{
csvContext.Write(personList, writer, csvFileDescription);
}
MessageBox.Show("Person has been added! " + "Person ID: " + personID);
LastNameBox.Clear();
FirstNameBox.Clear();
MiddleNameBox.Clear();
}
}
}
PersonFIles.csv
Person ID,Last Name,First Name,Middle Name
Person ID,Last Name,First Name,Middle Name
1,Sample Last,Sample First,Sample Middle
Person ID,Last Name,First Name,Middle Name
2,James,Lebron,King
1条答案
按热度按时间a64a0gku1#