0

每 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.
4

2 回答 2

3

清除项目后是否可以获得选定项目文本?

,您在清除后无法获得所选项目。这是非常明显的行为,因为我们可以获取集合中不存在的项目。该Clear方法使项目集合为空。您可以在清除之前保存项目唯一属性(如项目 ID)并稍后使用。

于 2013-11-11T07:50:37.333 回答
1

尝试这个:

var lbxActiveEmp = new ListBox(); // create new instance instead of using Clear();
lbxActiveEmp.DataTextField = "Name";
lbxActiveEmp.DataValueField = "EmpID";
于 2013-11-11T08:45:22.663 回答