我有一个带有一组值的 ListBox,如果数据被添加/删除,我想更新它。
以下工作,但有没有办法不必每次修改内容时都调用它?
lbUsers.DataSource = myDataSource;
lbUsers.DataBind();
如果数据被添加/删除,我想更新它
这一切都取决于您的表单 UI。
页面的重点是添加用户并在添加用户时显示它们吗?或者页面的指令是显示所有当前可用的用户,直到第二个?
如果您的目标是前者,那么您只需在lbUsers
每次添加用户时重新绑定 ListBox。
下面是第一种情况的示例:
添加用户和显示
标记
<asp:TextBox ID="txtUsername" runat="server" />
<asp:Button ID="btAdd" runat="server" value="Add" onclick="btAdd_Click" />
<asp:ListBox ID="lbUsers" runat="sever" />
代码隐藏
public void AddUser()
{
string username = txtUsername.Text;
// Either update the database with a new user
User newUser = User(username);
WhateverDataAccessYoureUsing.Add(User);
List<User> users = WhateverDataAccessYoureUsing.GetAllUsers();
lbUsers.DataSource = users;
lbUsers.DataBind();
// OTHER OPTION
//
// Or if no database directly bind the user to the ListBox
ListItem li = new ListItem(username);
lbUsers.Items.Add(li);
}
protected void btAdd_Click(object sender, EventArgs e)
{
AddUser();
}
但是,如果页面只是显示所有用户并显示在其他地方创建的新用户,那么您需要在AJAX
此处结合服务器端代码。我们将不使用服务器控件,而是使用 HTML 选择,因为无法在WebMethods
. 此外,我们将用于jQuery
调用AJAX
。
通过 AJAX 调用显示用户
标记
<select id="lbUsers" size="4" multiple="multiple">
</select>
<script>
// When the page is ready to be manipulated
$(function() {
// Call the server every three seconds to get an updated list of users
setInterval(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetUsers",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// If we are successful, append the results to lbUser
$(result.d).appendTo('#lbUser').hide().fadeIn(500);
},
error: function () {
// If we encounter an error, alert the user
alert("There was a problem getting the new users");
}
});
},3000); // 3000 is 3000 milliseconds which is 3 seconds
});
</script>
代码隐藏
// This annotation is required for all methods that can be accessed via AJAX calls
[System.Web.Services.WebMethod]
public static void GetUsers()
{
List<User> users = WhateverDataAccessYoureUsing.GetAllUsers();
string listItems = string.Empty;
// Loop through the list of users and create the option
// that will be displayed inside of lbUsers
foreach (User u in users)
{
listItems += CreateOption(u.Username);
}
// return the string value that will be appended on to lbUsers
return listItems;
}
// This creates the html options that will be displayed
// inside of lbUser
private string CreateOption(string text)
{
string option = "<option>" + text + "</option>"
}
是的,如果要显式添加项目,则不一定必须使用数据源:
lbUsers.Items.Add(new ListItem("New Item", "NI"));
您需要在每次回发时将数据源显式绑定到更新的数据源。