每5秒将新数据绑定到列表框,在绑定之前,我将使用Items.Clear()清除列表框中的现有数据。清除项目后,我无法从列表框中获取SelectedItem文本。
1)在PostBack之前加载数据,每次PostBack加载数据.....
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Not Loading Data on !IsPostBack condition, Every 5 seconds it will get new data.
}
LoadAciveEmployees();
}
2) Bind Values To ListBox
protected void LoadAciveEmployees()
{
DataTable dataContainer = (getting Data from sqlserver)
lbxActiveEmp.Items.Clear();
lbxActiveEmp.DataTextField = "Name";
lbxActiveEmp.DataValueField = "EmpID";
foreach (DataRow dr in dataContainer.Rows)
{
string empID = dr["EmpID"].ToString();
string name = dr["Name"].ToString();
lbxActiveEmp.Items.Add(new ListItem(name + " - " + empID, empID));
}
}
3) Get Selected Value from listtbox,
protected void getValue()
{
if (lbxActiveEmp.SelectedIndex != -1) //Based on this condition get selected value
{
selectedUser = lbxActiveEmp.SelectedItem.Text.ToString(); ***
}
}
*** -- After clearing the items, how get SelectedItem (text or value), Is it possible to get selected item text after items are cleared?
Please help me out from this issue.
答案 0 :(得分:3)
清除项目后是否可以获取所选项目文本?
否,清除后无法获取选中的项目。这是非常明显的行为,因为我们如何获得集合中不存在的项目。 Clear
方法使项集合为空。您可以在清算前保存项目唯一属性,例如项目ID,稍后再使用。
答案 1 :(得分:1)
试试这个:
var lbxActiveEmp = new ListBox(); // create new instance instead of using Clear();
lbxActiveEmp.DataTextField = "Name";
lbxActiveEmp.DataValueField = "EmpID";