在1.0版本中,紧接前面两节“增”、“删”、“查”代码,这里新增“改”功能
一、首先编辑好要修改的控件和相关属性,这里“编号”默认只读属性(ReadOnly)
二、其次,修改下窗体显示的代码,让数据直接显示出来,这里我们用一个方法封装好,直接在窗体加载事件(Load)中调用即可。
private void Form1_Load(object sender, EventArgs e){this.getRusult();}private void getRusult()//显示dataGridView1数据{string constr = "server=.;database=Students;user=sa;pwd=35683568";SqlConnection conn = new SqlConnection(constr);conn.Open();//textBox1.Text.Trim() textBox2.Text.Trim()string sql = "select Code as 用户id, Name as 用户名,Pwd as 密码,Sex as 性别,Age as 年龄,Phone as 手机号 from Temp_users";SqlDataAdapter adp1 = new SqlDataAdapter(sql, conn);DataSet ds = new DataSet();adp1.Fill(ds);//载入基本信息dataGridView1.DataSource = ds.Tables[0].DefaultView;conn.Close();}
三、通过点击DataGridView控件行,显示当前数据到待修改区,这里要写一个dataGridView1_RowHeaderMouseClick的事件
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)//点击DataGridView头部行{if (dataGridView1.SelectedCells.Count != 0){textBox1.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();textBox2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();textBox3.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();textBox4.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();textBox5.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();textBox6.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();}}
四、最后一步,点击按钮修改并提示成功更新,写button_click事件。
private void btnRevise_Click(object sender, EventArgs e)//修改{string constr = "server=.;database=Students;user=sa;pwd=35683568";SqlConnection conn = new SqlConnection(constr);conn.Open();int id = 0;int.TryParse(textBox1.Text, out id);string sql = "update Temp_users set Name = '" + textBox2.Text + "',Pwd = '" + textBox3.Text +"', Sex='"+textBox4.Text+"',Age="+textBox5.Text+",Phone="+textBox6.Text+" where Code = " + id;SqlCommand cmd = new SqlCommand(sql, conn);if (cmd.ExecuteNonQuery() > 0){this.getRusult();MessageBox.Show("更改成功!");}conn.Close();}