listbox selected item changed event fired two times

南笙酒味 提交于 2020-03-05 08:05:00

问题


Am using the below code for selected index changed event. Event fired two times i cant able to fix this error . Please help me to fix this error..

This is my code:

   if (ListBox1.Items.Count > 0)
   {
       for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
       {
           if (ListBox1.Items[i].Selected == true)
           {
               lblempid.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(0, 8));
               lblempname.Text = Convert.ToString(ListBox1.Items[i].Text.Substring(9));
               DataSet5TableAdapters.sp_GetallpayperiodTableAdapter TA = new DataSet5TableAdapters.sp_GetallpayperiodTableAdapter();
               DataSet5.sp_GetallpayperiodDataTable DS = TA.GetData();
               if (DS.Rows.Count > 0)
               {
                   fromdate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstartdate"]);
                   todate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldtodate"]);
                   status = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstatus"]);
                   if (status == "OPEN")
                   {
                       lblfromdate.Text = string.Format("{0:yyyy-MM-dd}", fromdate);
                       lbltodate.Text = string.Format("{0:yyyy-MM-dd}", todate);
                   }
               }

           }
       }
   }

回答1:


Look inside your Page_Load handler. If you're setting the selection of the list box in there, you need to bracket it thus:

if (!Page.IsPostBack)
{
    ListBox1.SelectedItem = "your old selection";
}

Otherwise you'll see the handler fire twice, as you describe.

Also: this is not an answer to your question, but you might want to get rid of that loop:

if (ListBox1.SelectedIndex == -1) return;

string theItem = ListBox1.SelectedItem.ToString();

lblempid.Text = theItem.Substring(0, 8);
lblempname.Text = theItem.Substring(9);
DataSet5TableAdapters.sp_GetallpayperiodTableAdapter TA 
    = new DataSet5TableAdapters.sp_GetallpayperiodTableAdapter();
DataSet5.sp_GetallpayperiodDataTable DS = TA.GetData();
if (DS.Rows.Count > 0)
{
    fromdate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstartdate"]);
    todate = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldtodate"]);
    status = Convert.ToString(DS.Rows[DS.Rows.Count - 1]["fldstatus"]);
    if (status == "OPEN")
    {
        lblfromdate.Text = string.Format("{0:yyyy-MM-dd}", fromdate);
        lbltodate.Text = string.Format("{0:yyyy-MM-dd}", todate);
    }
}


来源:https://stackoverflow.com/questions/11671916/listbox-selected-item-changed-event-fired-two-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!