C#winform視窗登錄和數據的增刪改查

来源:https://www.cnblogs.com/debugnotes/archive/2019/01/10/10249358.html
-Advertisement-
Play Games

工具:VS2013 資料庫SqlServer2008 兩張表,一個用戶登錄表,一個資料表用於增刪改查 。先把表建好。可以根據我發的圖建立,這樣下麵的代碼修改的就少。 資料部分SQL CREATE TABLE [dbo].[Customer]( [CustomerID] [varchar](20) N ...


工具:VS2013

資料庫SqlServer2008

兩張表,一個用戶登錄表,一個資料表用於增刪改查 。先把表建好。可以根據我發的圖建立,這樣下麵的代碼修改的就少。

資料部分SQL

 

CREATE TABLE [dbo].[Customer](
[CustomerID] [varchar](20) NOT NULL,
[CompanyName] [varchar](20) NULL,
[ContacName] [varchar](20) NULL,
[ContacTitle] [nchar](10) NULL,
[Address] [nchar](10) NULL,
[City] [nchar](10) NULL,
[Region] [nchar](10) NULL,
[PostalCode] [nchar](10) NULL,
[Country] [nchar](10) NULL,
[Phone] [nchar](10) NULL,
[Fax] [nchar](10) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

 

一、新建項目

  

二、拖入控制項,自己拖入,不用說了。

三、雙擊登錄按鈕,在雙擊方法裡面寫入下麵代碼。(form2是登錄成功跳轉到的頁面,順便新建一個就好了。裡面有輸入框什麼的名稱報錯,自己修改修改。改成和我一樣的就可以了。

最上面加入下麵的引用

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

 

private void button1_Click(object sender, EventArgs e)
{
string uername = textBox1.Text.Trim();
string pwd = textBox2.Text;
// 建立SqlConnection對象,根據你的資料庫,用戶名和密碼修改一下
SqlConnection con = new SqlConnection("server=LAPTOP-SVLMBJT3;database=Northwind;user=sa;pwd=sa");
// 打開連接
con.Open();
// 指定SQL語句,我是資料庫的一張表,用來測試登錄,自己建立一個表,
SqlCommand com = new SqlCommand("SELECT USERNAME,PASSWORD FROM tb_MYUSER where USERNAME='" + uername + "' and PASSWORD='" + pwd + "'", con);
// 建立SqlDataAdapter和DataSet對象
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
int n = da.Fill(ds, "tb_MYUSER");
if (n != 0)
{
MessageBox.Show("登錄成功!", "提示");
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
else
{
MessageBox.Show("用戶名或密碼錯誤,請重新輸入!", "提示");
textBox1.Text = "";
textBox2.Text = "";
textBox1.Focus();
}
con.Close();
}

四、就可以測試登錄了,登錄成功後就跳轉到from2了。下來我們做form2的視窗。

如果前面新建了form2就直接打開,沒有的話就新建一個。如下圖。一個MenuStrip按鈕,一個ComboBox下拉,一個TextBox,兩個按鈕,一個dataGridView裡面有兩個按鈕,一個刪除一個修改

在dataGridView1里設置兩個按鈕,一個刪除按鈕一個修改按鈕,新增用上面那個按鈕,點擊進入另一個頁面新增。

刪除按鈕

 

 修改按鈕

五、雙擊form2的頁面,加入下麵代碼,載入下拉查詢條件。

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

 

/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form2_Load(object sender, EventArgs e)
{
// 建立SqlConnection對象
//SqlConnection con = new SqlConnection("server=192.168.1.19;database=Northwind;user=MISTEST;pwd=MISTEST");
SqlConnection con = new SqlConnection("server=LAPTOP-SVLMBJT3;database=Northwind;user=sa;pwd=sa");
// 打開連接
con.Open();
// 指定SQL語句 
SqlCommand com = new SqlCommand("select distinct Country from Customer", con);
// 建立SqlDataAdapter和DataSet對象
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
comboBox1.Items.Add(sdr[0].ToString());//迴圈讀取數據
}
sdr.Close();// 關閉數據集
}

 六、雙擊查詢,我們來做查詢。寫入下麵的代碼

string strsql = "SELECT CustomerID as ID,CompanyName as 公司名稱 ,Country as 國家 ,ContacName as 聯繫人 , ContacTitle as 聯繫人稱呼, Address as 地址 ,City as 城市, Region as 地區 , PostalCode as 郵編 FROM Customer WHERE 1=1";//查詢語句。
if (comboBox1.Text != "")
{
strsql = strsql + " AND Country = '" + comboBox1.Text + "' ";
}
if (textBox2.Text != "")
{
strsql = strsql + " AND CompanyName LIKE '%" + textBox2.Text.ToUpper() + "%' ";
}
dataGridView1.DataSource = Utils.GetDataSet(strsql);
this.dataGridView1.Columns["cz"].DisplayIndex = this.dataGridView1.Columns.Count - 1;
this.dataGridView1.Columns["xg"].DisplayIndex = this.dataGridView1.Columns.Count - 2;

其中有一個Utils類是用於查詢,新增修改刪的。創建一個Utils類,

複製項目的代碼

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;

 

 

{
/// <summary>
/// 增刪改查
/// </summary>
class Utils
{
public static void Updatedata(string sql)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = sql;
SqlDataReader dr = com.ExecuteReader();//執行SQL語句
dr.Close();
con.Close();
}
public static DataTable GetDataSet(string safeSql)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["datebase"].ConnectionString.ToString();
try
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(safeSql, con);
cmd.CommandTimeout = 3000;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
if (ex.Message.Contains("連接超時時間已到"))
{
MessageBox.Show("連接伺服器超時!", "提示");
return null;
}
else
{
throw ex;
}

}
finally
{
if (con != null && con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
else if (con != null && con.State == System.Data.ConnectionState.Broken)
{
con.Close();
}
}
}
}
}

添加兩個引用

六、添加一個配置文件

打開配置文件加入下麵的代碼,也就是資料庫的連接,改成你自己的。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="datebase" connectionString="server=.;database=Northwind;uid=sa;pwd=sa" />
</connectionStrings>
</configuration>

 到這裡就可以查詢了,可以先在數據加一條數據用來測試。

七、新增,我們在建立一個form3  這樣做的好處是保存的時候好操作。如圖

加一個改造方法,修改的時候就可以把選到的那一列帶過來。

public Form3()
{
//用於判斷新增和修改。
arg = false;
InitializeComponent();
}

private string id;
private string name; private string country;
bool arg = false;
/// <summary>
/// 修改構造方法
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="country"></param>
public Form3(string id, string name, string country)
{
this.id = id;
this.name = name;
this.country = country;
arg = true;
InitializeComponent();
}

 

 給視窗綁定一個顯示事件

 

事件方法

private void Form3_Shown(object sender, EventArgs e)
{
if (arg)
{
if (id != null)
{
this.textBox1.Text = id;
this.textBox2.Text = name;
this.textBox3.Text = country;
}
}
}

點擊保存按鈕

 

private void button1_Click(object sender, EventArgs e)
{
if (arg)
{
//update
if ("".Equals(this.textBox1.Text.Trim()))
{
MessageBox.Show("id值不能為空");
return;
}
string sql1 = "delete from Customer where CustomerID='" + id + "'; insert into Customer(CustomerID,CompanyName,Country) values('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "');";
Utils.Updatedata(sql1);
MessageBox.Show("修改成功!");
this.Close();
}
else
{
//insert
string sql2 = " insert into Customer(CustomerID,CompanyName,Country) values('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.textBox3.Text + "');";
Utils.Updatedata(sql2);
MessageBox.Show("添加成功!");
this.Close();
}
}

八、回到form2 雙擊新增按鈕,打開新增頁面,就可以測試新增了。

代碼

Form3 f = new Form3();
f.ShowDialog();

九、下來我們做修改和刪除。在form2裡面給dataGridView加個點擊事件,用來刪除和修改

 

 點擊事件代碼

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewColumn colunm = this.dataGridView1.Columns[e.ColumnIndex];
if (colunm is DataGridViewButtonColumn)
{
string text = colunm.HeaderText;
if ("刪除操作".Equals(text.Trim()))
{
string str = this.dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString().Trim();
string sql = "delete from Customer where CustomerID='" + str + "'";
try
{
Utils.Updatedata(sql);
MessageBox.Show("刪除成功!", "提示");
button1_Click(sender, e);
}
catch (Exception)
{

}
}
if (colunm is DataGridViewButtonColumn)
{
string id = this.dataGridView1.Rows[e.RowIndex].Cells["ID"].Value.ToString().Trim();
string name = this.dataGridView1.Rows[e.RowIndex].Cells["公司名稱"].Value.ToString().Trim();
string Country = this.dataGridView1.Rows[e.RowIndex].Cells["國家"].Value.ToString().Trim();
string text1 = colunm.HeaderText;
if ("修改操作".Equals(text1.Trim()))
{
Form3 f = new Form3(id, name, Country);
f.ShowDialog();

button1_Click(sender, e);
}
}
}
}
}
}
}

 

可以測試了

完事了。寫的不好,有疑問可以加微信或者QQ都是 78474580

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • wpf中的WebBrowser相比之前的winform閹割了不少東西,也增加了不少東西,但是msdn對wpf也沒有較好的文檔 WebBrowser可以說是一個.NET控制項,相對於WPF中的控制項,不在同一線程,它們不可重疊,相當於兩個獨立的視窗`(window ...
  • 0x01 前言 在滲透測試的時候各種PHP版的一句話木馬已經琳琅滿目,而.NET平臺下的一句話木馬則百年不變,最常見的當屬下麵這句 筆者感覺有必要挖坑一下.NET平臺里的一句話木馬,經過一番摸索填坑終於可以總結出了.NET下的三駕馬車,於是乎有了這個系列的文章。今天是第一篇著重介紹一般處理程式 (A ...
  • 1.zookeeper簡單介紹 1.1作用 zookeeper的作用是存儲kafka的伺服器信息,topic信息,和cunsumer信息。如下圖: 而zookeeper是個什麼東西呢?簡單來說就是一個具有通知機制的文件系統,引用網路上的一張圖 可以看出來zookeeper是一個樹形的文件結構,我們可 ...
  • MVC圖片上傳--控制器方法 新建一個控制器命名為File,定義一個Img方法 [HttpPost]public ActionResult Img(HttpPostedFileBase shangchuan){string path = @"\upload\" + DateTime.Now.ToFi ...
  • 程式在Visual Studio設計的很清晰的菜單和界面,運行的時候菜單和控制項上字體變得很模糊,界面大小也發生了變化 解決方法是:更改程式的配置文件,使程式運行時自動檢測屏幕解析度,在高分屏時禁用系統縮放,微軟已經為我們考慮了很多,WinForm預設清單文件里已經加入了對禁用高分屏自動縮放的支持,只 ...
  • 孔雀東南飛 作者:佚名 (漢) 序曰:漢末建安中, 廬江府小吏焦仲卿妻劉氏,為仲卿母所遣, 自誓不嫁。其家逼之, 乃投水而死。仲卿聞之, 亦自縊於庭樹。時人傷之, 為詩云爾。孔雀東南飛,2019-01-10 五里一徘徊。“十三能織素, 十四學裁衣,十五彈箜篌, 十六誦詩書。十七為君婦, 心中常苦悲。 ...
  • 故事起源 本來今天想寫.NET Core實戰之CMS系統第十五篇文章的。哈,奈何今天在新生命人脈群裡面看到石頭哥分享的一張圖片,然後大家就議論了起來,不過我看的很懵逼,這圖什麼意思啊?當一個朋友講述了這個圖片背後的故事的時候,瞬間淚奔了!先上圖,第一眼看很平淡,一個苦逼程式猿在加班,旁邊那個是布娃娃 ...
  • IIS (安裝SSL證書後) 實現 HTTP 自動跳轉到 HTTPS ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...