//删除选中行 private void Deletedata() { string stridcolumname = dgrdUp.Columns[0].HeaderText; //获取主键名 string value = dgrdUp.Rows[dgrdUp.CurrentRow.Index].Cells[0].Value.ToString(); //获取选中行第一列值 string deletesql = "delete from " + tablename + " where " + stridcolumname + "='" + value + "'"; AppServer.ExecuteNonQuery(deletesql); //再更新datagridview dt = AppServer.SelData(sql); SelectTodgv(); }
//单元格内容改变 private void dgrdUp_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { string strcomm; //sql string stridcolumname = dgrdUp.Columns[0].HeaderText; //获取主键名 string strcolumn = dgrdUp.Columns[e.ColumnIndex].HeaderText; //获取列标题 string strrow = dgrdUp.Rows[e.RowIndex].Cells[0].Value.ToString(); //获取焦点触发行的第一个值 string value = dgrdUp.CurrentCell.Value.ToString(); //获取当前点击的活动单元格的值 if (e.ColumnIndex == 0 && dgrdUp.Columns[0].HeaderText.ToLower() == "id") { MessageBox.Show("ID列不能输入数值!"); dgrdUp.CurrentCell.Value = null; return; } //判断是否是空行 if ((newrowid - 1) == e.RowIndex && datarownull(e.RowIndex, e.ColumnIndex)) { //如果新增的不是第一列 并且第一列不是id列 提示需要先新增第一列 if (e.ColumnIndex != 0 && dgrdUp.Columns[0].HeaderText.ToLower() != "id") { MessageBox.Show("需要先输入 " + stridcolumname + " 的值!"); return; } strcomm = "insert into " + tablename + " (" + strcolumn + ") values('" + value + "')"; } else { //第一列不能编辑 if (e.ColumnIndex == 0) { MessageBox.Show("第一列" + stridcolumname + "的值不能编辑!"); return; } strcomm = "update " + tablename + " set " + strcolumn + " ='" + value + "' where " + stridcolumname + " = '" + strrow + "'"; } AppServer.ExecuteNonQuery(strcomm); //再更新datagridview dt = AppServer.SelData(sql); SelectTodgv(); } catch (Exception ee) { MessageBox.Show(ee.Message.ToString()); } }