asp.net 對資料庫表增加,刪除,編輯更新修改

来源:http://www.cnblogs.com/luxiaoyao/archive/2016/11/23/6093919.html
-Advertisement-
Play Games

web.config <configuration> <connectionStrings> <add name="constr" connectionString="server=.\sqlexpress;database=db2016;uid=sa;pwd=123;" /> <add name= ...


  1 using System;
  2 using System.Collections.Generic;
  3 using System.Configuration;
  4 using System.Data;
  5 using System.Data.SqlClient;
  6 using System.Linq;
  7 using System.Web;
  8 using System.Web.UI;
  9 using System.Web.UI.WebControls;
 10 
 11 public partial class _Default : System.Web.UI.Page
 12 {
 13     private string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
 14 
 15     SqlHelper helper = new SqlHelper();
 16     protected void Page_Load(object sender, EventArgs e)
 17     {
 18         if (!Page.IsPostBack)
 19         {
 20             using (SqlConnection conn = new SqlConnection(constr))
 21             {
 22     
 23                  SqlDataAdapter ad = new SqlDataAdapter("select * from tbuser", conn);
 24                  SqlCommandBuilder builder = new SqlCommandBuilder(ad);
 25                  DataTable dt = new DataTable();
 26                  ad.Fill(dt);
 27                  this.GridView1.DataSource = dt;
 28                  this.DataBind();
 29             }
 30         }
 31     }
 32 
 33     private void userlistbind()
 34     {
 35         GridView1.DataSource = helper.SelectSqlReturnDataset("select id, username as '用戶名',birthday  as '生日', '部門號'=(select departmentname from tbdepartment where tbdepartment.departmentid=tbUser.departmentid) from tbUser").Tables[0];
 36     }
 37     protected void btnAdd_Click(object sender, EventArgs e)
 38     {
 39 
 40         string sql = "insert into tbUser(username,birthday,departmentid) values('" + txtUserName.Text + "','" + txtBirthday.Text + "'," + ddlDepartment.SelectedValue.ToString() + ")";
 41         int count = helper.ExecuteReturnInt(sql, null, System.Data.CommandType.Text);
 42         if (count != 0)
 43         {
 44             userlistbind();
 45             Response.Write("<script>alert('數據添加成功!')</script>");
 46             txtBirthday.Text = "";
 47             txtUserName.Text = "";
 48             
 49             GridView1.DataBind();
 50         }
 51     }
 52     protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
 53     {
 54        
 55       
 56        
 57     }
 58     protected void bind()
 59     {
 60         SqlConnection myconn = new SqlConnection(constr);
 61         myconn.Open();
 62         string sql = "select id,username 用戶名,birthday 生日,departmentid 部門號 from tbUser";
 63         SqlDataAdapter myda = new SqlDataAdapter(sql, myconn);
 64         DataSet myds = new DataSet();
 65         myda.Fill(myds);
 66         GridView1.DataSource = myds;
 67         GridView1.DataKeyNames = new string[] { "id" };
 68         GridView1.DataBind();
 69         myda.Dispose();
 70         myds.Dispose();
 71         myconn.Close();
 72     }
 73 
 74    
 75 
 76 
 77     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 78     {
 79         GridView1.EditIndex = e.NewEditIndex;
 80         this.bind();
 81     }
 82     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 83     {
 84        
 85         int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
 86         string name = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString();
 87         string birthday = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString();
 88         string department = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString();
 89         string sql = "update tbUser set username='" + name + "',birthday='"+birthday+"',departmentid="+department+" where id=" + id + "";
 90         SqlConnection myconn = new SqlConnection(constr);
 91         myconn.Open();
 92         SqlCommand mycmd = new SqlCommand(sql, myconn);
 93         mycmd.ExecuteNonQuery();
 94         mycmd.Dispose();
 95         myconn.Close();
 96         GridView1.EditIndex = -1;
 97         this.bind();
 98     }
 99     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
100     {
101         GridView1.EditIndex = -1;
102         this.bind();
103     }
104     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
105     {
106         int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
107         string sql = "delete from tbUser where id=" + id + "";
108         SqlConnection myconn = new SqlConnection(constr);
109         myconn.Open();
110         SqlCommand mycmd = new SqlCommand(sql, myconn);
111         mycmd.ExecuteNonQuery();
112         mycmd.Dispose();
113         myconn.Close();
114         GridView1.EditIndex = -1;
115         this.bind();
116     }
117     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
118     {
119 
120         if (e.Row.RowType == DataControlRowType.DataRow)
121         {
122             ((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "return confirm('確定要刪除嗎')");
123         }
124     }
125 }

web.config

<configuration>
<connectionStrings>
<add name="constr" connectionString="server=.\sqlexpress;database=db2016;uid=sa;pwd=123;" />
<add name="db2016ConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=db2016;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>

</configuration>

 

 

GridView的datakeyname屬性 設為id

 

 

資料庫表

create table tbUser

(
id int primary key identity(1,1),
username nvarchar(20),
userpass varbinary(128),
birthday datetime,
departmentid int foreign key references tbdepartment(departmentid)
)


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

-Advertisement-
Play Games
更多相關文章
  • 前言 日常用Python多一些,不過很多時候shell腳本更簡單實用一些,所以有必要熟悉一下shell腳本。當然shell有他特定的一些場景,比方說我曾經改過一個vpn斷線自動重連的 "腳本" ,簡單實用。 另: 本文比較簡單,算是入門簡述,類似於30分鐘入門的東西,想詳細看的可以去搜其他文章,很多 ...
  • 設置 NLS_LANG 變數 1) 正確配置 LC_ALL 參數 2) 配置 telnet/ssh/SecureCRT 客戶端的字元集 linux中可以用locale命令來查看 NLS_LANG設置,如下例所示 [root@HXZG ~]# locale LANG=en_US.UTF-8 LC_CT ...
  • #Elaine:master;Dylan:minion#利用salt給minion安裝包[root@elaine states]# vim /etc/salt/master 1 default_include: master.d/*.conf 2 3 interface: 0.0.0.0 4 5 ' ...
  • InfluxDB每秒可以處理成千上萬條數據,要將這些數據全部保存下來會占用大量的存儲空間,有時我們可能並不需要將所有歷史數據進行存儲,因此,InfluxDB推出了數據保留策略(Retention Policies),用來讓我們自定義數據的保留時間。更多InfluxDB詳細教程請看:InfluxDB系 ...
  • 基礎監控的同比告警主要是針對伺服器監控採集的指標,包括負載(load1/load5/load15)、平均CPU使用率、記憶體使用率、內外網流量、埠數量等,具體採集方法可參考《基礎監控-伺服器監控》。 一、告警原理 多個指標每分鐘1個數據,比較當前分鐘的前10分鐘的7天平均值,如果幅度超過100%並且 ...
  • make,make install都是典型的使用GNU的AUTOCONF和AUTOMAKE產生的程式的安裝步驟。 make是用來編譯的,在命令行輸入make命令之後,系統會在當前目錄下搜索Makefile或者makefile文件,它從Makefile中讀取指令,然後編譯。make install是用 ...
  • linux shell可以識別4種不同類型的引字元號: 單引號字元' 雙引號字元" 反斜杠字元\ 反引號字元` 1. 單引號 ( '' )# grep Susan phonebook Susan Goldberg 403-212-4921 Susan Topple 212-234-2343 如果我們 ...
  • 在Ubuntu中第一次使用VIM編輯器發現好強大,打算在Win7中安裝,其中遇到一些小問題,下邊介紹詳細的安裝過程和遇到的問題。 1-安裝 首先發現Github中有一款中意的作者,並且他開源的基本插件都集合了。 地址:https://github.com/DemonCloud/Aix-Vim(下載地 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...