Datagridview控件之前端界面操作数据表
一、 知识点描述
GridView 是 DataGrid的后继控件,在.net framework 2 中,虽然还存在DataGrid,但是GridView已经走上了历史的前台,取代DataGrid的趋势已是势不可挡。GridView和DataGrid功能相似,都是在web页面中显示数据源中的数据,将数据源中的一行数据,也就是一条记录,显示为在web页面上输出表格中的一行。,
二、 思维导图
三、 示例代码
1、 数据库连接字符串
SqlConnection sqlConnection2 = new SqlConnection();
sqlConnection2.ConnectionString = DBHelper.connString;
2、 载入数据表
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = DBHelper.connString; //
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM Prescription;";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataTable studentTable = new DataTable();
sqlConnection.Open();
sqlDataAdapter.Fill(studentTable);
sqlConnection.Close();
this.dgv_drug.DataSource = studentTable;
3、 增加命令
insertCommand.Connection = sqlConnection2;
insertCommand.CommandText =
"INSERT Prescription"
+ "(PrescriptionNo,PrescriptionName,PrescriptionPrice)"
+ " VALUES(@No,@Name,@Price);";
insertCommand.Parameters.Add("@No", SqlDbType.Char, 10, "PrescriptionNo");
insertCommand.Parameters.Add("@Name", SqlDbType.VarChar, 0, "PrescriptionName");
insertCommand.Parameters.Add("@Price", SqlDbType.VarChar, 0, "PrescriptionPrice");
4、 更新命令
SqlCommand updateCommand = new SqlCommand();
updateCommand.Connection = sqlConnection2;
updateCommand.CommandText =
"UPDATE Prescription"
+ " SET PrescriptionNo=@No,PrescriptionName=@Name,PrescriptionPrice=@Price"
+ " WHERE PrescriptionNo=@OldNo;";
updateCommand.Parameters.Add("@No", SqlDbType.Char, 10, "PrescriptionNo");
updateCommand.Parameters.Add("@Name", SqlDbType.VarChar, 0, "PrescriptionName");
updateCommand.Parameters.Add("@Price", SqlDbType.VarChar, 0, "PrescriptionPrice");
updateCommand.Parameters.Add("@OldNo", SqlDbType.Char, 10, "PrescriptionNo"); updateCommand.Parameters["@OldNo"].SourceVersion = DataRowVersion.Original;
5、 删除命令
SqlCommand deleteCommand = new SqlCommand();
deleteCommand.Connection = sqlConnection2;
deleteCommand.CommandText =
"DELETE Prescription"
+ " WHERE PrescriptionNo=@No;";
deleteCommand.Parameters.Add("@No", SqlDbType.Char, 10, "PrescriptionNo");
四、 效果截图

![clip_image002[6] clip_image002[6]](https://img2018.cnblogs.com/blog/1240475/201810/1240475-20181024190055650-694048473.jpg)
![clip_image003[6] clip_image003[6]](https://img2018.cnblogs.com/blog/1240475/201810/1240475-20181024190058560-1659041199.png)
浙公网安备 33010602011771号