要使用ASP.NET和SQL Server來(lái)創(chuàng)建一個(gè)簡(jiǎn)易留言板,你可以按照以下步驟進(jìn)行操作:
創(chuàng)建一個(gè)ASP.NET網(wǎng)站項(xiàng)目:
創(chuàng)建留言板數(shù)據(jù)庫(kù):
在ASP.NET中連接到數(shù)據(jù)庫(kù):
<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實(shí)例名稱。創(chuàng)建留言板頁(yè)面:
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;
}
在頁(yè)面上顯示留言:
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();
}
}
}
}
通過(guò)以上步驟,你就可以使用ASP.NET和SQL Server創(chuàng)建一個(gè)簡(jiǎn)易的留言板了。請(qǐng)記得根據(jù)你的具體需求進(jìn)行適當(dāng)?shù)恼{(diào)整和修改。