0

我将以下代码用于选定的索引更改事件。事件触发了两次,我无法修复此错误。请帮我解决这个错误..

这是我的代码:

   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);
                   }
               }

           }
       }
   }
4

1 回答 1

0

查看您的 Page_Load 处理程序内部。如果您在其中设置列表框的选择,则需要将其括起来:

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

否则,正如您所描述的,您将看到处理程序触发两次。

另外:这不是您问题的答案,但您可能想摆脱那个循环:

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);
    }
}
于 2012-07-26T14:54:57.887 回答