我想创建一个显示数据库记录的应用程序,我可以添加新记录。我第一次在C#中使用数据库,所以我在这个主题中完全不喜欢。当我点击按钮接受时,比编译器显示“发生未处理的异常。”。我不知道我做错了什么。 我的代码:
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string CellPhoneNumber { get; set; }
public string EMailAddress { get; set; }
public Person() { }
public Person(string firstName, string lastName, string address, string cellPhoneNumber, string eMailAddress)
{
FirstName = firstName;
LastName = lastName;
Address = address;
CellPhoneNumber = cellPhoneNumber;
EMailAddress = eMailAddress;
}
}
public class PersonDatabase
{
public SQLiteConnection connection;
static string baseName = "Person.db";
static string basePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
static string path = Path.Combine(basePath, baseName);
public PersonDatabase()
{
// If database don't exist then, will created new file. Else open exist file.
if (!File.Exists(path))
{
connection = new SQLiteConnection(path);
connection.CreateTable<Person>();
}
connection = new SQLiteConnection(path);
}
public PersonDatabase(Person person) : base()
{
//person.Id = connection.Table<Person>().Count() + 1;
connection.Insert(person);
connection.Update(person);
}
}
public class MainActivity : Activity
{
public PersonDatabase database = new PersonDatabase();
private List<Person> personList = new List<Person>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var addButton = FindViewById<Button>(Resource.Id.addButton);
var query = database.connection.Table<Person>();
foreach (var person in query)
{
personList.Add(person);
}
var listView = FindViewById<ListView>(Resource.Id.listView);
listView.Adapter = new ListViewAdapter(this, personList);
addButton.Click += (object sender, EventArgs e) =>
{
StartActivity(typeof(FormActivity));
};
}
}
[Activity(Label = "FormActivity")]
public class FormActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Form);
var firstName = FindViewById<EditText>(Resource.Id.editTextFirstName);
var lastName = FindViewById<EditText>(Resource.Id.editTextLastName);
var address = FindViewById<EditText>(Resource.Id.editTextAddress);
var cellPhoneNumber = FindViewById<EditText>(Resource.Id.editTextCellNumber);
var eMailAddress = FindViewById<EditText>(Resource.Id.editTextMail);
var acceptButton = FindViewById<Button>(Resource.Id.acceptButton);
acceptButton.Click += (object sender, EventArgs e) =>
{
Person newPerson = new Person(firstName.Text, lastName.Text, address.Text, cellPhoneNumber.Text, eMailAddress.Text);
var personDatabase = new PersonDatabase(newPerson);
StartActivity(typeof(MainActivity));
Finish();
};
}
}