帮我用ASP.NET生成一段代码,一个后台页面有条件和查询按钮可以显示从数据库查询显示的数据
时间: 2024-05-07 12:16:46 浏览: 101
好的,以下是ASP.NET生成的代码示例。你可以根据你的具体需求进行修改。
```html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ASP.NET 数据库查询页面</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>ASP.NET 数据库查询页面</h1>
<h2>查询条件:</h2>
<asp:DropDownList ID="ddlCategory" runat="server">
<asp:ListItem Text="分类1" Value="1"></asp:ListItem>
<asp:ListItem Text="分类2" Value="2"></asp:ListItem>
<asp:ListItem Text="分类3" Value="3"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<h2>查询结果:</h2>
<asp:GridView ID="gvData" runat="server"></asp:GridView>
<br /><br />
<asp:Button ID="btnSearch" runat="server" Text="查询" OnClick="btnSearch_Click" />
</div>
</form>
</body>
</html>
```
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
// 从数据库查询数据
string connectionString = "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True";
string query = "SELECT * FROM YourTable WHERE CategoryId = @categoryId";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@categoryId", ddlCategory.SelectedValue);
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
gvData.DataSource = dataTable;
gvData.DataBind();
}
}
}
}
```
请确保将 `YourDatabase` 和 `YourTable` 替换为你自己的数据库和表名。
阅读全文