iT邦幫忙

0

ASP.NET & C# 表格列當月日曆

請問我想做到使用表格或div的方式
一列一列的列出"當月:例:現在是五月會列出1~31列的div日期"
並有兩攔,一欄是顯示日期,一欄是放置textbox讓使用者輸入資料,可以依照所填的textbox的改對應日期,抓取日期及textbox的內文一併將有資料的textbox寫入到MSSQL呢?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
kent3513
iT邦新手 5 級 ‧ 2011-06-02 10:53:45

把TextBox的Name和日期設一樣,那你就可以判斷出哪一個TextBox是哪一天的。

0
JamesDoge
iT邦高手 1 級 ‧ 2022-12-29 01:18:03

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();
        }
    }
}

我要發表回答

立即登入回答