//保存更新数据 private void button2_Click(object sender, EventArgs e) { //1.采集用户输入 TblClass model = new TblClass(); model.TClassID = Convert.ToInt32(lblid.Text); model.TClassName = textEditName.Text.Trim(); model.TClassDesc = textEditClassDesc.Text.Trim(); //2.连接数据库,执行更新 string constr = "Data Source=DESKTOP-J4JFLTU\\SQLEXPRESS;Initial CataLog=MyFirstDataBase;Integrated Security=True"; using (SqlConnection con = new SqlConnection(constr)) { string sql = string.Format("update TblClass set tClassName='{0}',tClassDesc='{1}' where tClassid={2}" , model.TClassName, model.TClassDesc, model.TClassID); using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); int r = cmd.ExecuteNonQuery(); this.Text = "更新了" + r + "行"; //重新加载,绑定DataGridView LoadData(); } } }
private void LoadData() { List <TblClass> list = new List <TblClass>(); string constr = "Data Source=DESKTOP-J4JFLTU\\SQLEXPRESS;Initial CataLog=MyFirstDataBase;Integrated Security=True"; using (SqlConnection con = new SqlConnection(constr)) { string sql = "select * from tblclass"; using (SqlCommand cmd = new SqlCommand(sql, con)) { con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows)//是否查询到数据 { //一条一条读取数据,自动下移 while (reader.Read()) { TblClass model = new TblClass(); model.TClassID = reader.GetInt32(0); model.TClassName = reader.GetString(1); model.TClassDesc = reader.IsDBNull(2)?"NULL":reader.GetString(2); list.Add(model);//把读取到的数据加载到list集合中 } } } } } //数据绑定的时候只认属性,不认字段,内部通过反射实现 this.dgvClass.DataSource = list;//数据绑定 }
//行获取焦点事件,sender表示整个窗口控件事件 private void dgvClass_RowEnter(object sender, DataGridViewCellEventArgs e) { //获取当前选中的行的对象 DataGridViewRow currentRow = this.dgvClass.Rows[e.RowIndex]; //获取当前行中绑定的Tblclass数据对象 TblClass model = currentRow.DataBoundItem as TblClass;//转换类型 if (model != null) { lblid.Text = model.TClassID.ToString(); textEditName.Text = model.TClassName; textEditClassDesc.Text = model.TClassDesc; } }