CalendarForm.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CalendarForm.aspx.cs" Inherits="CalendarForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Calendar Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Date</td>
<td>Description</td>
</tr>
<!-- 用迴圈輸出每日日期及textbox -->
<% for (int i = 1; i <= 31; i++) { %>
<tr>
<td><%= i %></td>
<td><asp:TextBox ID="txtDescription" runat="server"></asp:TextBox></td>
</tr>
<% } %>
</table>
<asp:Button ID="btnSave" Text="Save" OnClick="btnSave_Click" runat="server" />
</div>
</form>
</body>
</html>
CalendarForm.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class CalendarForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 在頁面載入時執行程式碼
btnSave_Click(null, null);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
// 連接到MSSQL資料庫
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString))
{
conn.Open();
// 執行INSERT INTO語法,將有資料的textbox內容寫入到資料庫中
int i = 0;
foreach (Control ctrl in form1.Controls)
{
if (ctrl is TextBox && !String.IsNullOrEmpty((ctrl as TextBox).Text))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Calendar (Date, Description) VALUES (@Date, @Description)", conn);
cmd.Parameters.AddWithValue("@Date", DateTime.Today.AddDays(i));
cmd.Parameters.AddWithValue("@Description", (ctrl as TextBox).Text);
cmd.ExecuteNonQuery();
}
i++;
}
conn.Close();
}
}
}