这是我的代码,我想实现在datagridview编辑数据时能自动保存新增和已修改的数据到数据库,我用的是CurrentCellChanged事件。但这个代码一启动就报错!说是this.dataGridView1.CurrentRow为NULL,于是我在绑定数据前取消事件绑定,但还是不起作用!!!有没有什么好的办法?
public partial class CPModel : Form
{
private DataSet myDS;
private OleDbConnection conn=null;
private OleDbDataAdapter da = null;
private void binddata()
{
conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0.;Data Source=F:/CPDB.mdb");
conn.Open();
string sql = "select * from OriginData";
da = new OleDbDataAdapter(sql, conn);
myDS = new DataSet();
da.Fill(myDS,"OD");
this.dataGridView1.CurrentCellChanged -= new EventHandler(dataGridView1_CurrentCellChanged);
this.dataGridView1.DataSource = myDS.Tables["OD"].DefaultView;
this.dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.RowHeadersVisible = false;
}
public CPModel()
{
InitializeComponent();
binddata();
}
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (this.dataGridView1.CurrentRow.IsNewRow)
{
da.InsertCommand = conn.CreateCommand();
da.InsertCommand.CommandText = "insert into OriginData values(@Phases,@SpCode)";
da.InsertCommand.Parameters.Add("@Phases", OleDbType.VarChar, 10, "Phases");
da.InsertCommand.Parameters.Add("@SpCode", OleDbType.VarChar, 10, "SpCode");
int count = da.Update(myDS, "OD");