使用以下代码选择索引更改事件。事件被解雇了两次我无法修复此错误。请帮我解决这个错误。
这是我的代码:
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);
}
}
}
}
}
答案 0 :(得分: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);
}
}