列表框所选项目更改事件被触发两次 [英] listbox selected item changed event fired two times
本文介绍了列表框所选项目更改事件被触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将以下代码用于选定的索引更改事件.事件触发了两次,我无法修复此错误.请帮助我解决此错误..
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..
这是我的代码:
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);
}
}
}
}
}
推荐答案
查看您的Page_Load处理程序.如果要在其中设置列表框的选择,则需要将其括在方括号中:
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);
}
}
这篇关于列表框所选项目更改事件被触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文