【发布时间】:2023-03-25 04:55:02
【问题描述】:
我有一个搜索功能,可以在我的 OleDb 数据库中查找特定用户。对于每个用户,都会在表中创建一行,其中包含他的姓名、布尔值表示他是否是管理员以及一个删除按钮。删除按钮没有按预期工作,它不执行链接到它的方法。我的代码位于 Search_Click 事件中,该事件在管理员单击搜索按钮以搜索特定用户后立即执行。 我试图从我的代码中放置一个预定义的按钮,但在 Page_Load 中,它按预期工作。我怎样才能让按钮也从 Search_Click 工作? 基本上,在根据用户搜索文本动态创建 LinkButtons 并单击搜索按钮 (Search_Click) 之后,我需要找到一种方法来在页面加载事件上注册 click 事件,我不知道该怎么做,因为 linkbuttons 必须在搜索按钮的点击事件中创建,但它们也必须通过页面加载进行注册。
using (OleDbDataReader reader = cmd.ExecuteReader())
{
Table table = new Table();
TableRow row = new TableRow();
TableCell cell = new TableCell();
Label label = new Label();
while (reader.Read())
{
row = new TableRow();
cell = new TableCell();
label = new Label();
label.Text = reader.GetString(0);
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
label = new Label();
label.Text = reader.GetBoolean(1).ToString();
cell.Controls.Add(label);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
cell = new TableCell();
LinkButton button = new LinkButton();
button.Text = "Delete";
button.ID = (string) reader["uName"];
button.CommandName = (string)reader["uName"];
button.Click += new EventHandler(DeleteUser);
cell.Controls.Add(button);
cell.BorderStyle = BorderStyle.Solid;
row.Cells.Add(cell);
table.Rows.Add(row);
}
table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
TableHolder.Controls.Add(table);
}
删除用户:
protected void DeleteUser(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
string path = Server.MapPath(@"App_Data/ArcadeDatabase.accdb");
using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Persist Security Info = False;"))
{
try
{
con.Open();
}
catch(Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
if(con.State == System.Data.ConnectionState.Open)
{
using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con))
{
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
helper.Log("OleDbError", ex.Message);
}
}
}
con.Dispose();
}
path = "";
}
catch (Exception ex)
{
helper.Log("Admin", ex.Message);
}
}
【问题讨论】:
-
这段代码似乎没有问题。您至少需要提供 DeleteUser 事件的代码。
-
我已经编辑了我的问题,它现在包含 DeleteUser 代码:) 但正如我所说,我放置了一个断点,它甚至没有执行。