<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="互联网_.WebForm1" %>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <link rel="stylesheet" type="text/css" href="StyleSheet1.css" /> </head> <body> <form id="form1" runat="server"> <div> <div class="se"> <span>车位状态:</span> <asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddl"> <asp:ListItem Value="0">Occupied</asp:ListItem> <asp:ListItem Value="1">Available</asp:ListItem> </asp:DropDownList> <span>车位主:</span> <asp:DropDownList ID="DropDownList2" runat="server" CssClass="ddl" DataSourceID="SqlDataSource1" DataTextField="OwnerID" DataValueField="OwnerID"></asp:DropDownList> <span>空闲时段:</span> <asp:DropDownList ID="DropDownList3" runat="server" CssClass="ddl" DataSourceID="SqlDataSource1" DataTextField="WeekdayOpenTime" DataValueField="WeekdayOpenTime"></asp:DropDownList> <asp:Button ID="Button1" CssClass="se-btn" runat="server" Text="搜索" OnClick="Button1_Click" /> <asp:Button ID="Button2" CssClass="re-btn" runat="server" Text="重置" OnClick="Button2_Click" /> </div> <div class="se"> <asp:Button ID="Button3" CssClass="add-btn" runat="server" Text="添加" /> <asp:Button ID="Button4" CssClass="de-btn" runat="server" Text="删除" OnClick="Button4_Click" OnClientClick="return confirm('你确定要删除选中的记录吗?');"/> </div> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" CssClass="ta" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ParkingSpaceID" HeaderText="车位ID" SortExpression="ParkingSpaceID" />
<asp:BoundField DataField="Status" HeaderText="车位状态" SortExpression="Status" />
<asp:BoundField DataField="Price" HeaderText="价格" SortExpression="Price" />
<asp:BoundField DataField="WeekdayOpenTime" HeaderText="开始时间" SortExpression="WeekdayOpenTime" />
<asp:BoundField DataField="WeekdayCloseTime" HeaderText="结束时间" SortExpression="WeekdayCloseTime" />
<asp:BoundField DataField="OwnerID" HeaderText="车位主ID" SortExpression="OwnerID" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button5" CssClass="re-btn" runat="server" Text="修改" />
<asp:Button ID="Button6" CssClass="de-btn" runat="server" Text="删除" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ParkingSystem (3)ConnectionString %>" SelectCommand="SELECT [ParkingSpaceID], [Status], [Price], [WeekdayOpenTime], [WeekdayCloseTime], [OwnerID] FROM [ParkingSpaces]"></asp:SqlDataSource>
</div>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace 互联网_ { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataKeyNames = new string[] { "ParkingSpaceID" }; // 修改为与页面GridView绑定的主键一致 } }
protected void Button1_Click(object sender, EventArgs e)
{
string query = "SELECT [ParkingSpaceID], [Status], [Price], [WeekdayOpenTime], [WeekdayCloseTime], [OwnerID] FROM [ParkingSpaces] WHERE 1 = 1";
if (DropDownList1.SelectedValue != "")
{
int statusValue = DropDownList1.SelectedValue == "1" ? 1 : 0;
query += " AND [Status] = @Status";
SqlDataSource1.SelectParameters.Add("Status", statusValue);
}
if (DropDownList2.SelectedValue != "")
{
query += " AND [OwnerID] = @OwnerID";
SqlDataSource1.SelectParameters.Add("OwnerID", DropDownList2.SelectedValue);
}
if (DropDownList3.SelectedValue != "")
{
query += " AND [WeekdayOpenTime] = @WeekdayOpenTime";
SqlDataSource1.SelectParameters.Add("WeekdayOpenTime", DropDownList3.SelectedValue);
}
System.Diagnostics.Debug.WriteLine("Button1 Query: " + query);
SqlDataSource1.SelectCommand = query;
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
if (dv.Count == 0)
{
// 如果没有查询到符合条件的数据,显示提示信息
Response.Write("<script>alert('未查询到符合条件的内容');</script>");
}
else
{
GridView1.DataBind();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
// 重置DropDownList相关操作
DropDownList2.DataSourceID = "SqlDataSource1";
DropDownList2.DataBind();
DropDownList3.DataSourceID = "SqlDataSource1";
DropDownList3.DataBind();
DropDownList1.SelectedIndex = 0;
// 重新绑定GridView
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void Button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox checkBox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (checkBox.Checked)
{
string parkingSpaceID = GridView1.DataKeys[i].Value.ToString();
string deleteQuery = "DELETE FROM ParkingSpaces WHERE ParkingSpaceID = @ParkingSpaceID";
cmd = new SqlCommand(deleteQuery, conn);
cmd.Parameters.AddWithValue("@ParkingSpaceID", parkingSpaceID);
cmd.ExecuteNonQuery();
}
}
}
// 重新绑定GridView,显示更新后的数据
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
Thank you for sharing your ASP.NET WebForms code. I've analyzed both the .aspx and the code-behind file. Here are some observations and suggestions for improvement:
Here's an example of how you could improve the Button4_Click event handler:
protected async void Button4_Click(object sender, EventArgs e)
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["myconnstr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
await conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM ParkingSpaces WHERE ParkingSpaceID = @ParkingSpaceID";
cmd.Parameters.Add("@ParkingSpaceID", SqlDbType.Int);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox checkBox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (checkBox.Checked)
{
int parkingSpaceID = Convert.ToInt32(GridView1.DataKeys[i].Value);
cmd.Parameters["@ParkingSpaceID"].Value = parkingSpaceID;
await cmd.ExecuteNonQueryAsync();
}
}
}
}
// Rebind GridView to show updated data
GridView1.DataBind();
}
catch (Exception ex)
{
// Log the exception
// Display user-friendly error message
Response.Write("<script>alert('An error occurred while deleting records.');</script>");
}
}
This improved version:
Remember to update the method signature in the .aspx file to match the async version:
<asp:Button ID="Button4" CssClass="de-btn" runat="server" Text="删除" OnClick="Button4_Click" OnClientClick="return confirm('你确定要删除选中的记录吗?');" UseSubmitBehavior="false" />
These suggestions should help improve the functionality, maintainability, and security of your application. Let me know if you have any questions or if you'd like me to elaborate on any specific area!
{"entities":[{"entity_type":2,"entity_content":{"file":null,"image":{"key":"tos-cn-i-a9rns2rl98/7c69c7f640c84445a0341698761463b3.png","image_thumb":null,"image_ori":{"url":"https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/7c69c7f640c84445a0341698761463b3.png~tplv-a9rns2rl98-resize-jpeg-v1.png?rk3s=1fb89129\u0026x-expires=1735614495\u0026x-signature=n7u9CWad43P0br5Z8r%2BvHADenmA%3D","format":"","width":0,"height":0},"image_raw":null,"image_thumb_ori":null,"preview_img":null,"feedback":null,"request_id":"","rephrase_prompt":"","md5":"","identifier":"4410be40-c1a4-11ef-8f3f-3dfbd954af4b","description":""},"directory":null},"identifier":"4410be40-c1a4-11ef-8f3f-3dfbd954af4b","file_name_state":null,"file_parse_state":null}],"text":"运行代码出现如下报错"}
I understand you're encountering an error when running your code. Let me translate and explain the error message from the image:
Error message translation: "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid object name 'ParkingSpaces'."
This error suggests that the database table 'ParkingSpaces' doesn't exist or is not accessible in your SQL Server database. This could be due to several reasons:
To resolve this issue, you should:
Now, let's create a React component that demonstrates how to properly handle database operations and potential errors. This example will use a mock API instead of a real database connection, but the principles remain the same:
This React component demonstrates several best practices:
To use this component in your Next.js application:
This implementation should help you avoid the "Invalid object name" error by properly handling database operations and potential errors. Remember to always validate user input and use parameterized queries to prevent SQL injection attacks when working with real databases.