0

我想在我的网站上设置搜索功能。用户在文本框中键入一些信息并单击搜索按钮。单击搜索按钮后,使用文本框中的文本搜索数据库,并将结果显示在表格中。如果文本框中的文本与数据库中的一个结果完全匹配,而不是显示结果列表,页面将填充有关匹配结果的详细信息。

为了更容易准确地匹配结果,我想在每个“选择”结果的结果旁边添加一个按钮,用该结果的文本填充文本框,从而用详细信息填充页面。这就是我所拥有的。

单击搜索按钮后,在检查结果是否完全匹配后,我创建了一个包含结果和按钮的表:

for(int x=0; x < res_list.Length; x++)
{
     TableRow newRow = new TableRow();
     TableCell textCell = new TableCell();
     TableCell buttonCell = new TableCell();
     buttonCell.ID = "bc" + x;
     Button cellButton = new Button();
     cellButton.ID = "btn" + x;
     textCell.Text = res_list[x];
     textCell.Attributes.Add("Width","60%");
     cellButton.Text = x.ToString();

     // cellButton.OnClientClick = "NameClick"; This property refers to client-side scripts, which I am not using.
     cellButton.Click += new EventHandler(NameClick);

     buttonCell.Controls.Add(cellButton);
     newRow.Cells.Add(firstCell);
     newRow.Cells.Add(buttonCell);
     myTable.Rows.Add(newRow);
}

我已经尝试过上面看到的 OnClientClick 方法和 Click 方法,两者都产生了相同的结果。

我的 NameClick 函数如下:

void NameClick(object sender, EventArgs e)
{
     Button sendButton = (Button)sender;
     int index = Int32.Parse(sendButton.Text);
     SearchTextBox.Text = myTable.Rows[index].Cells[0].Text;
     return;
}

我在 NameClick 函数的开头设置了一个断点,当我单击其中一个按钮时,它永远不会到达。为什么我的按钮没有调用这个函数?

编辑:如果可能的话,我想在不使用 JavaScript 的情况下完成此操作。

4

4 回答 4

4

您使用cellButton.OnClientClick = "NameClick";,但NameClick您的 javascript 中实际上有一个函数吗?如果没有,单击该按钮将导致 JS 错误,这可能会阻止回发。

除此之外,建议将显式 ID 分配给您以编程方式创建的控件。否则,自动生成的 ID 可能会在回发时更改,这将阻止触发控制事件。

类似以下的东西应该可以工作(未经测试):

myTable.ID = "someid";
for (int x=0; x < res_list.Length; x++)
{
  TableRow newRow = new TableRow();
  newRow.ID = "r" + x;
  TableCell textCell = new TableCell();
  TableCell buttonCell = new TableCell();
  buttonCell.ID = "bc" + x;
  Button cellButton = new Button();
  cellButton.ID = "btn" + x;
  textCell.Text = res_list[x];
  textCell.Attributes.Add("Width","60%");
  cellButton.Text = x.ToString();

  //cellButton.OnClientClick = "NameClick"; // not needed unless you have actual JS for it
  cellButton.Click += new EventHandler(NameClick);

  buttonCell.Controls.Add(cellButton);
  newRow.Cells.Add(firstCell);
  newRow.Cells.Add(buttonCell);
  myTable.Rows.Add(newRow);
}
于 2012-03-21T21:22:16.210 回答
1

cellButton.OnClientClick应该指向一个客户端函数,即JavaScript。你在某处有 JS 函数吗?

如果答案是否定的,那么我们已经找到了您的问题。你应该创建一个。ClientIDMode将动态生成的控件的属性设置为Staticor会很有帮助Predictable,因此您的 JS 函数可以轻松访问它们。

您需要 JS 功能的帮助吗?

于 2012-03-21T21:27:52.207 回答
1

当你点击按钮时,页面重新开始生命周期并且你的控件在页面中不存在你需要重新创建控件或者保存在viewstate中或者在生命周期中回调时使用控件状态

在页面生命周期事件SaveControlState、loadControlState

如果你想创建一个javascript点击事件,你需要确保控件不会在javascript函数中为此调用服务器端事件,你需要返回false

于 2012-03-21T22:00:43.023 回答
-2

您必须在您的 asp 语法中为按钮添加此事件。

 <asp:Button runat="server " OnClick="ButtonClick"/>
于 2012-03-21T21:21:07.473 回答