本文提供完整的 ASP.NET Web Forms 範例,展示如何使用 C# 實作資料庫的新增、修改、刪除與分頁查詢功能,包含前端 Default.aspx 與後端 Default.aspx.cs 完整程式碼。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>資料庫 CRUD 操作示範</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" PageSize="5"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID編號">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="name" HeaderText="使用者名稱">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="pwd" HeaderText="密碼">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="datatime" DataFormatString="{0:yyyy年MM月dd日}" HeaderText="時間" HtmlEncode="False">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="id" DataNavigateUrlFormatString="Default.aspx?id={0}"
HeaderText="編輯" Text="編輯" />
<asp:CommandField HeaderText="刪除" ShowDeleteButton="True" />
</Columns>
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
</asp:GridView>
<br />
<asp:Label ID="Label1" runat="server" Width="324px"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="新增資料" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="修改資料" OnClick="Button2_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
private const string ConnStr = "Server=(local);User Id=sa;Pwd=860712;Database=snear";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindGrid();
if (Request.QueryString["id"] != null)
{
LoadRecordForEdit(Request.QueryString["id"]);
}
}
private void BindGrid()
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tb_Info", conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "tb_Info");
GridView1.DataSource = ds;
GridView1.DataKeyNames = new string[] { "id" };
GridView1.DataBind();
}
}
private void LoadRecordForEdit(string id)
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tb_Info WHERE id=@id", conn);
adapter.SelectCommand.Parameters.AddWithValue("@id", id);
DataSet ds = new DataSet();
adapter.Fill(ds, "tb_Info");
if (ds.Tables["tb_Info"].Rows.Count > 0)
{
DataRow row = ds.Tables["tb_Info"].Rows[0];
TextBox1.Text = row["name"].ToString();
TextBox2.Text = row["pwd"].ToString();
Label1.Visible = true;
Label1.Text = $"您目前要修改第 [{id}] 筆記錄!";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string sql = "INSERT INTO tb_Info (name, pwd) VALUES (@name, @pwd)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name", TextBox1.Text);
cmd.Parameters.AddWithValue("@pwd", TextBox2.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
BindGrid();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text)
&& Request.QueryString["id"] != null)
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string sql = "UPDATE tb_Info SET name=@name, pwd=@pwd WHERE id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name", TextBox1.Text);
cmd.Parameters.AddWithValue("@pwd", TextBox2.Text);
cmd.Parameters.AddWithValue("@id", Request.QueryString["id"]);
conn.Open();
cmd.ExecuteNonQuery();
}
Label1.Visible = false;
TextBox1.Text = TextBox2.Text = "";
BindGrid();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string sql = "DELETE FROM tb_Info WHERE id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id);
conn.Open();
cmd.ExecuteNonQuery();
}
BindGrid();
}
}
SqlParameter 防止 SQL 注入(原始碼採用字串串接有風險,已修正)PageIndexChanging 事件處理換頁此範例展示傳統 Web Forms 資料綁定模式,現代專案建議考慮 Entity Framework Core + ASP.NET Core MVC/Razor Pages 架構。