如上图:
修改dataGridView中的值后点击保存,提示不能插入重复值!点击保存的代码如下:
 private void TS_Save_Click(object sender, EventArgs e)
        {
            int i = this.dataGridView1.CurrentRow.Index;
            if (i > -1)
            {
                try
                {
                    SqlCommand InsertComm = new SqlCommand("insert into J_Regional2(RegBid,RegBName,RegAid,comment) values(@RegBid,@RegBName,@RegAid,@comment)", operation.conn());
                    InsertComm.Parameters.Add("@RegBid", SqlDbType.NVarChar, 10, "RegBid");
                    InsertComm.Parameters.Add("@RegBName", SqlDbType.NVarChar, 20, "RegBName");
                    InsertComm.Parameters.Add("@RegAid", SqlDbType.NVarChar, 10, "RegAid");
                    InsertComm.Parameters.Add("@comment", SqlDbType.NVarChar, 50, "comment");                    SqlCommand UpdateComm = new SqlCommand("update J_Regional2 set RegBid=@RegBid,RegBName=@RegBName,RegAid=@RegAid,comment=@comment where RBid=" + this.dataGridView1.Rows[i].Cells[0].Value + "", operation.conn());
                    UpdateComm.Parameters.Add("@RegBid", SqlDbType.NVarChar, 10, "RegBid");
                    UpdateComm.Parameters.Add("@RegBName", SqlDbType.NVarChar, 20, "RegBName");
                    UpdateComm.Parameters.Add("@RegAid", SqlDbType.NVarChar, 10, "RegAid");
                    UpdateComm.Parameters.Add("@comment", SqlDbType.NVarChar, 50, "comment");                    ADP.InsertCommand = InsertComm;
                    ADP.UpdateCommand = UpdateComm;
                    SqlCommandBuilder Builder = new SqlCommandBuilder(ADP);
                    ADP.Update(ds.Tables["RegB"]);
                    ds.Tables["RegB"].Clear();
                    getDate();
                }
                catch (SqlException se)
                {
                    MessageBox.Show(se.ToString());
                }
            }
            else
            {
                MessageBox.Show("索引ID不能为-1!","提示",MessageBoxButtons.OK,MessageBoxIcon.Stop);
            }
        }表结构:
     自动ID:    [RBid]     [int]        自动增长列,主键   非空
     编号:      [RegBid]   [nvarchar] (10)   有唯一约束   非空   
     名称:      [RegBName] [nvarchar] (10)                非空
     区域编号:  [RegAid]   [nvarchar] (10)                非空
     备注:      [comment]  [nvarchar] (50) 

解决方案 »

  1.   

    调试看下该行的状态
    使用SqlCommandBuilder貌似不用那么麻烦,只需要指定查询语句就行了,增加,修改和删除语句会自动根据查询语句生成的
      

  2.   

    是的啊,现在就是指定了:插入、修改的SQL语句啊,没有做其它什么啊
    然后就是数据库同步了,呵呵
      

  3.   

    你try{}catch能捕捉到这个异常吧?
    就在catch那里输出"新增失败,可能是某字段重复了"
    你全部都写在一起
    只能这样了
      

  4.   


    SqlCommandBuilder  可以自动调用是插入还是修改的,不需要单独指定,只需指定SQL语句就可以了