1. 程式人生 > >基於DevExpress的C#窗體應用程式設計—資料庫的簡單增刪改查

基於DevExpress的C#窗體應用程式設計—資料庫的簡單增刪改查

1.開啟Microsoft Visual Studio,點選檔案,新建專案,選擇C#窗體應用程式
新建專案
建立C#窗體應用程式
2.將Form1重新命名為StuManager,更改窗體StuManager的Text屬性為學生資訊
對窗體重新命名
修改窗體左上角顯示
3.在工具箱選擇工具LayoutControl,放至窗體中(ps:按住滑鼠左鍵,拉動滑鼠將控制元件框住,點選左上角方向標可移動控制元件位置),接著在工具箱選擇控制元件TextEdit,新增至窗體中(ps:根據實際修改控制元件的Name屬性),根據所需的TextEdit控制元件數量進行新增,最後新增控制元件SimpleButton(ps:注意修改控制元件的Name屬性)
工具LayoutControl
將LayoutControl放至窗體中
控制元件TextEdit


加入一個TextEdit的結果
新增TextEdit控制元件結束
新增SimpleButton
4.雙擊submit按鈕,在Click事件中新增程式碼,整體程式碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace StuManager
{
    public
partial class StuManager : Form { public StuManager() { InitializeComponent(); } private void btnSubmit_Click(object sender, EventArgs e) { //明確資料庫在哪兒:包括伺服器、資料庫的名字、使用者的名字及密碼 string connString = "server=.;database=資料庫名字;user id = 使用者名稱;password=密碼"
; //SQL連線上connString SqlConnection conn = new SqlConnection(connString); //開啟資料庫連線 conn.Open(); //SqlDataAdapter是 DataSet和 SQL Server之間的橋接器,用於檢索和儲存資料 SqlDataAdapter sqlDa = new SqlDataAdapter("select * from tb_Stu", conn); // DataTable表示記憶體中資料的一個表 DataTable dt = new DataTable(); //使用SqlDataAdapter的Fill方法(填充),呼叫select命令 sqlDa.Fill(dt); //select :選取表 tb_Stu中的第一行的id屬性的值 MessageBox.Show(dt.Rows[0]["id"].ToString()); //update 更新表 tb_Stu中的資料-更新id='201631061108'對應的name為'sweet' string updateStr = "update tb_Stu set name='sweet' where id='201631061108'"; SqlCommand comUpdate = new SqlCommand(updateStr,conn); int resultUpdate = comUpdate.ExecuteNonQuery(); MessageBox.Show("The total update number is : " + resultUpdate.ToString()); //delete 刪除表 tb_Stu中的資料-id='201631061104'所在行 string deleteStr = "delete from tb_Stu where id='201631061104'"; SqlCommand comDelete = new SqlCommand(deleteStr,conn); int resultDelete = comDelete.ExecuteNonQuery(); MessageBox.Show("The total delete number is : "+resultDelete.ToString()); //insert 根據文字輸入框中內容進行資料輸入,並驗證txtID(長度為12且需輸入數字) string str = txtID.Text; Regex r = new Regex("^[0-9]*$"); Match m = r.Match(str); if (!m.Success) { MessageBox.Show("Please input numbers!"); } else { //其中txtID、 txtName、txtAge、txtPWD均為對應TextEdit控制元件的Name string insertStr = "insert into tb_Stu values('" + txtID.Text + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtPWD.Text + "')"; SqlCommand cmdInsert = new SqlCommand(insertStr, conn); int resultInsert = cmdInsert.ExecuteNonQuery(); MessageBox.Show("The total insert number is : " + resultInsert.ToString()); } //關閉資料庫連線 conn.Close(); } } }