要使用ASP.NET和SQL Server來創建一個簡易留言板,你可以按照以下步驟進行操作:
創建一個ASP.NET網站項目:
創建留言板數據庫:
在ASP.NET中連接到數據庫:
<connectionStrings>
<add name="MessageBoardDB" connectionString="Data Source=<your_server_name>;Initial Catalog=MessageBoard;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<your_server_name>
替換為你的SQL Server實例名稱。創建留言板頁面:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string email = txtEmail.Text;
string message = txtMessage.Text;
string connectionString = ConfigurationManager.ConnectionStrings["MessageBoardDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "INSERT INTO Messages (Name, Email, Message, CreatedDate) VALUES (@Name, @Email, @Message, GETDATE())";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Email", email);
command.Parameters.AddWithValue("@Message", message);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
// 清空表單字段
txtName.Text = string.Empty;
txtEmail.Text = string.Empty;
txtMessage.Text = string.Empty;
}
在頁面上顯示留言:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["MessageBoardDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "SELECT * FROM Messages ORDER BY CreatedDate DESC";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
gridMessages.DataSource = reader;
gridMessages.DataBind();
}
connection.Close();
}
}
}
}
通過以上步驟,你就可以使用ASP.NET和SQL Server創建一個簡易的留言板了。請記得根據你的具體需求進行適當的調整和修改。