今天的作业是用winfrom窗体做一个留言板,如图:
要求和数据库有查询和添加功能。下拉框里的值是直接获取数据库中的值
一、连接数据库,获取表中数据
1 //创建一个存数据的表 2 DataTable table = new DataTable(); 3 string liuyanConn = "server=.;integrated security=true;database=DataGridView"; 4 string liuyanSql = "select UserName as 用户名 ,Content as 留言内容 from UserInfo"+ //两张表联合查询 +" inner join MessageInfo on MessageInfo.UserId=UserInfo.UserId"; 5 SqlConnection sqlConn = new SqlConnection(liuyanConn); 6 SqlCommand sqlComm = new SqlCommand(liuyanSql, sqlConn); 7 8 SqlDataAdapter da = new SqlDataAdapter(sqlComm); 9 da.Fill(table);10 this.dataGridView1.DataSource = table;
二、获取数据库中的用户名,并赋值到下拉列表中
1 //下拉菜单 2 string liuyanSql2 = "select * from UserInfo"; 3 sqlConn.Open(); 4 SqlCommand command = new SqlCommand(liuyanSql2, sqlConn); 5 SqlDataReader reader = command.ExecuteReader(); 6 while (reader.Read()) 7 { 8 string name = (String)reader["UserName"]; 9 this.comboBox1.Items.Add(name);10 }11 sqlConn.Close();
三、将选的留言对象和留言内容存到数据库中,然后更新界面
//添加留言 SqlConnection sqlConn2 = new SqlConnection(liuyanConn); sqlConn2.Open(); string liuyanSql2 = string.Format("insert into MessageInfo(Content,UserId) values ('{0}',{1})",this.textBox1.Text, id); SqlCommand command2 = new SqlCommand(liuyanSql2, sqlConn2); int i = command2.ExecuteNonQuery(); sqlConn2.Close(); if (i > 0) { MessageBox.Show("留言成功!"); } xianshi();
难点:1、将数据库中的值取出来,然后赋值到下拉列表中
2、用户信息和留言内容不是一个表,由外键相连着
因此需要根据表1中的用户名查询到用户编号,然后再将用户编号和留言内容存到表2中
這就多涉及一次查询,插入
ps:這次代码写得相当的啰嗦,慢慢再改吧