使用开发工具 VS 2022 C#,数据库MS SQL SERVER 2019 ,基于NET WinForms,实现数据记录的创建(Create)、更新(Update)、读取(Read)和删除(Delete)等功能。主要控件包括:DataGridView,SqlDataApater , DataTable , bingingSource和DataSet。
1.WinForms界面
2.使用SqlDataApater + DataSet + DataGridView 读取数据
private void ReadData()
{//数据库连接串string strConn = "Data Source=127.0.0.1;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=*********;Encrypt=False";SqlConnection conn = null;try{conn = new SqlConnection(strConn);conn.Open();//打开数据库string sql = "select * from TestTask order by 1";SqlDataAdapter sda = new SqlDataAdapter(sql, conn); //创建SqlDataAdapter类的对象System.Data.DataSet ds = new System.Data.DataSet();//创建DataSet类的对象sda.Fill(ds);//使用SqlDataAdapter对象sda将查新结果填充到DataSet对象ds中dataGridView1.DataSource = ds.Tables[0];//设置表格控件的DataSource属性//设置数据表格上显示的列标题//dataGridView1.Columns[0].HeaderText = "编号";//设置数据表格为只读dataGridView1.ReadOnly = true;//不允许添加行dataGridView1.AllowUserToAddRows = false;//背景为白色dataGridView1.BackgroundColor = Color.White;//只允许选中单行dataGridView1.MultiSelect = false;//整行选中dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;}catch (Exception ex){MessageBox.Show("加载数据错误!" + ex.Message);}finally{if (conn != null){conn.Close();//关闭数据库连接}}
}
3.根据查询条件查询数据
if (textBox1.Text != "")//textBox1.Text为查询条件
{string strConn = "Data Source=127.0.0.1;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=********;Encrypt=False";//创建SqlConnection的实例SqlConnection conn = null;try{conn = new SqlConnection(strConn);conn.Open(); //打开数据库string sql = "select * from TestTask where 检测编号 like '%{0}%'";sql = string.Format(sql, textBox1.Text);/填充占位符SqlDataAdapter sda = new SqlDataAdapter(sql, conn);//创建SqlDataAdapter类的对象DataSet ds = new DataSet();//创建DataSet类的对象sda.Fill(ds);//使用SqlDataAdapter对象sda将查新结果填充到DataSet对象ds中dataGridView1.DataSource = ds.Tables[0];//设置表格控件的DataSource属性}catch (Exception ex){MessageBox.Show("查询数据出错!" + ex.Message);}finally{if (conn != null){//关闭数据库连接conn.Close();}}
}
4.2.使用SqlDataApater + DataTable + bingingSource + DataGridView 读取数据
string strConn = "Data Source=127.0.0.1;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=********;Encrypt=False";
SqlConnection con = null;
con = new SqlConnection(strConn);
con.Open();
string strSql = "select * from testtask";
SqlDataAdapter ada = new SqlDataAdapter(strSql, con);
DataTable myTable = new DataTable();
ada.Fill(myTable);bindingSource1.DataSource = myTable;this.dataGridView1.DataSource = bindingSource1;