问题
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