我是C#的新手,我想问一下为什么按下OK按钮时它不运行?有一条错误消息。这是我的表单数据代码,其中包含OK按钮:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Bab_8___LINQ_to_SQL_Classes
{
public partial class DataForm : Form
{
Person _temporaryPerson;
public Person TemporaryPerson {
get {
return _temporaryPerson;
}
}
public DataForm()
{
InitializeComponent();
this.Text = "Add New Person";
_temporaryPerson = new Person();
}
public DataForm(Person person)
{
InitializeComponent();
this.Text = "Edit Person Data";
_temporaryPerson = person;
txtName.Text = TemporaryPerson.Name;
txtAddress.Text = TemporaryPerson.Address;
txtPhone.Text = TemporaryPerson.PhoneNumber;
}
private void btnOK_Click(object sender, EventArgs e)
{
_temporaryPerson.Name = txtName.Text;
_temporaryPerson.Address = txtAddress.Text;
_temporaryPerson.PhoneNumber = txtPhone.Text;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}
然后这是主窗体,即具有 LINQ to SQL 命令:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Bab_8___LINQ_to_SQL_Classes
{
public partial class Form1 : Form
{
private AddressbookDBDataContext db;
public Form1()
{
InitializeComponent();
db = new AddressbookDBDataContext();
UpdateViewer();
}
private void UpdateViewer() {
dgView.DataSource = (from p in db.Persons select p).ToList();
}
private void btnAdd_Click(object sender, EventArgs e)
{
DataForm dataForm = new DataForm();
if (dataForm.ShowDialog() == DialogResult.OK) {
db.Persons.InsertOnSubmit(dataForm.TemporaryPerson);
db.SubmitChanges();
UpdateViewer();
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
int selectedIndex = (int)dgView.CurrentRow.Cells[0].Value;
Person selectedPerson = (from p in db.Persons where p.PersonID == selectedIndex select p).FirstOrDefault();
DataForm dataForm = new DataForm(selectedPerson);
if (dataForm.ShowDialog() == DialogResult.OK) {
db.SubmitChanges();
UpdateViewer();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int selectedIndex = (int)dgView.CurrentRow.Cells[0].Value;
Person selectedPerson = (from p in db.Persons where p.PersonID == selectedIndex select p).FirstOrDefault();
if (MessageBox.Show
("Do you want to delete this data?", "Delete Data",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
db.Persons.DeleteOnSubmit(selectedPerson);
db.SubmitChanges();
UpdateViewer();
}
}
}
}
我真的很想解决这个问题。