在DGV中更新行记录数据:效果如下图:
-
#region 在DataGridView中更新相关行数据
-
private void ButtonUpdate_Click(object sender, EventArgs e)
-
{
-
string dbconn = configxml.xmlconn.readxml(); //读取连接数据库存配置
-
SqlConnection sqlcon = new SqlConnection(dbconn);
-
-
if (dataGridView1.DataSource == null || dataGridView1.CurrentRow == null)
-
{
-
return;
-
}
-
else
-
{
-
if (this.dataGridView1.SelectedRows.Count > 0)
-
{
-
DialogResult dr = MessageBox.Show("确定更新表中的数据记录? ", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
-
if (dr == DialogResult.OK)
-
{
-
try
-
{
-
sqlcon.Open(); ; //打开数据库连接
-
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows) //遍历所选中的dataGridView记录行
-
{
-
string strId = row.Cells[0].Value.ToString();//取数据库的ID行记录
-
string strName = row.Cells[1].Value.ToString(); //取dataGridView1中的第2列的值
-
string strFirstname = row.Cells[2].Value.ToString();//取dataGridView1中的第3列的值
-
string strPosition = row.Cells[3].Value.ToString();//取dataGridView1中的第4列的值
-
string strPhone = row.Cells[4].Value.ToString();//取dataGridView1中的第5列的值
-
MessageBox.Show(strId+strName+strFirstname+strPosition+strPhone);
-
string sql = string.Format("update T_users set username='{0}',FirstName='{1}',Position='{2}',Telphone='{3}' where ID='{4}'", strName,strFirstname,strPosition,strPhone,strId);
-
//SQL语句来执行要求操作
-
SqlCommand cmd = new SqlCommand(sql, sqlcon); //执行sqlcommand上面sql语句
-
cmd.ExecuteNonQuery(); //执行删除操作
-
cmd.Dispose();
-
}
-
}
-
catch (Exception ex)
-
{
-
MessageBox.Show(ex.ToString(), "提示");
-
}
-
finally
-
{
-
sqlcon.Close(); //关闭数据库连接
-
}
-
this.ButtonFresh_Click(this.t_usersTableAdapter.Fill(this.misds.T_users), null);
-
//删除后执行刷新操作ButtonFresh是刷新按钮的名字
-
}
-
else
-
{
-
return;
-
}
-
}
-
}
-
}
-
#endregion
阅读(3848) | 评论(0) | 转发(0) |