我有一个ListBox的一组值,我想要更新它,如果数据被添加/删除它。asp.net列表框更新
以下工作,但有没有办法不必每次修改内容时调用它?
lbUsers.DataSource = myDataSource;
lbUsers.DataBind();
我有一个ListBox的一组值,我想要更新它,如果数据被添加/删除它。asp.net列表框更新
以下工作,但有没有办法不必每次修改内容时调用它?
lbUsers.DataSource = myDataSource;
lbUsers.DataBind();
您需要将数据源显式绑定在每一个回发到更新的数据源。
''绑定列表
我想获得它更新,如果数据被添加/删除它
这一切都取决于你的表单UI。
是页面添加用户并在添加时显示它们的要点?或者是页面的指令显示所有当前可用的用户到第二个?
如果您的目标是前者,那么您每次添加用户时都会重新绑定lbUsers
列表框。
下面是下面的第一种情况的一个示例:
添加用户和显示
标记
<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>"
}
你怎么知道数据被修改,什么是“myDataSource”的类型? –
数据源来自数据库中的存储过程,并且它位于!isPostBack中。我不介意使用.DataSource和.DataBind(无论如何,只发生在两个地方)我只是想知道是否有一种方法可以只调用一次。 –