//添加数据按钮 private void btnAdd_Click(object sender, EventArgs e) { //先把数据保存到一个ClassInfo类 ClassInfo info = new ClassInfo(); info.className = tBClassName.Text.Trim(); info.classDesc = tBClassDesc.Text.Trim(); string sql = "insert into newTable output inserted.tClassId values(@name,@desc)";//能得到主键值 //创建参数数组,为了给sql语句中的参数赋值 //这里仅设定SqlParameter对象是属于什么参数的,这个参数的类型 SqlParameter[] parameter = new SqlParameter[]{ new SqlParameter("@name",SqlDbType.VarChar,50), new SqlParameter("@desc",SqlDbType.VarChar,50) }; //这里是赋值 parameter[0].Value = info.className; parameter[1].Value = info.classDesc; //把主键值赋值给info,这样所有成员都赋值了 info.classId = (Int32)SqlHelper.ExecuteScalar(sql, parameter); //加入到list中 list.Add(info); MessageBox.Show("添加成功"); }
//窗体载入时把数据读取到dateGridView private void Form1_Load(object sender, EventArgs e) { list = new BindingList<ClassInfo>(); string sql = "select * from newTable"; using (SqlDataReader reader = SqlHelper.ExecuteDateReader(sql)) { if (reader.HasRows) { while (reader.Read()) { ClassInfo info = new ClassInfo(); //把读取到的数据保存到一个ClassInfo类对象 info.classId = reader.GetInt32(0); info.className = reader.GetString(1); info.classDesc = reader.GetString(2); list.Add(info);//把这个info加入到list中 } } } dataGridView1.DataSource = list;//数据绑定 }