要使用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创建一个简易的留言板了。请记得根据你的具体需求进行适当的调整和修改。