//数据添加按钮 private void btnAdd_Click(object sender, EventArgs e) { //可空列 tSName, tSAddress, tSPhone, tSAge, tSBirthday, tSCardId //可填写列tSName, tSGender, tSAddress, tSPhone, tSAge, tSBirthday, tSCardId, tSClassId //获取输入,把数据保存到一个student类中 Student s = new Student(); s.tSName = txttSName.Text == "" ? "NULL" : "'" + txttSName.Text + "'"; s.tSGender = "'" + cbBGender.Text + "'"; s.tSAddress = txttSAddress.Text == "" ? "NULL" : "'" + txttSAddress.Text + "'"; s.tSPhone = txttSPhone.Text == "" ? "NULL" : "'" + txttSPhone.Text + "'"; s.tSAge = txttSAge.Text == "" ? null : (int?)int.Parse(txttSAge.Text); s.tSbirthday = dateTimePicker1.Value ; s.tSCardId = txttSCardId.Text == "" ? "NULL" : "'" + txttSCardId.Text + "'"; s.tSClassId=int.Parse(cbBClass.SelectedValue.ToString()); using (SqlConnection sc = new SqlConnection(constr)) { //这个语句能返回新增的行的主键值 string sqlsentence = string.Format("insert into TblStudent output inserted.tSId values({0},{1},{2},{3},{4},'{5}',{6},{7})", s.tSName, s.tSGender, s.tSAddress, s.tSPhone, s.tSAge == null ? "null" : s.tSAge.ToString(), s.tSbirthday.Value.ToString(), s.tSCardId, s.tSClassId); using (SqlCommand command = new SqlCommand(sqlsentence, sc)) { sc.Open(); //获得新增行的主键值 s.tSId = Convert.ToInt16(command.ExecuteScalar()); } } //s成员全部填满,把它加入到stulist stulist.Add(s); MessageBox.Show("添加成功"); }
//数据加载方法 private void DataInclude() { stulist = new BindingList<Student>(); using (SqlConnection sc = new SqlConnection(constr)) { string sqlSentence = @"select * from TblStudent"; using (SqlCommand scmand = new SqlCommand(sqlSentence, sc)) { sc.Open(); using (SqlDataReader reader = scmand.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { Student stu = new Student(); stu.tSId = reader.GetInt32(0); stu.tSName = reader.IsDBNull(1) ?null:reader.GetString(1); stu.tSGender = reader.IsDBNull(2) ? null : reader.GetString(2); stu.tSAddress = reader.IsDBNull(3) ? null : reader.GetString(3); stu.tSPhone = reader.IsDBNull(4) ? null : reader.GetString(4); stu.tSAge = reader.IsDBNull(5) ? null : (int?)reader.GetInt32(5); stu.tSbirthday = reader.IsDBNull(6) ? null : (DateTime?)reader.GetDateTime(6); stu.tSCardId = reader.IsDBNull(7) ? null : reader.GetString(7); stu.tSClassId = reader.GetInt32(8); stulist.Add(stu); } } } } } //用BindingList进行数据绑定 dataGridView1.DataSource = stulist; }