C# 若我将listbox刷新方法移动到页面加载中,listboxselectedindex将停止工作
我正在使用ASP.NET,我有一个刷新按钮。一个列表框。两个文本框。在.cs方面,我有一个方法,它清除列表框并刷新列表框,如果我将其放入页面加载,listbox selectedindexchanged事件将停止工作。为什么会这样C# 若我将listbox刷新方法移动到页面加载中,listboxselectedindex将停止工作,c#,asp.net,listbox,C#,Asp.net,Listbox,我正在使用ASP.NET,我有一个刷新按钮。一个列表框。两个文本框。在.cs方面,我有一个方法,它清除列表框并刷新列表框,如果我将其放入页面加载,listbox selectedindexchanged事件将停止工作。为什么会这样 using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection cnn = new SqlConnection("Initial Catalog=bigum;Data Source=localhost;Integrated Security=SSPI;");
protected void refresh()
{
ListBox1.Items.Clear();
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT OgrenciFirstName,OgrenciLastName FROM ogrenciler", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ListBox1.Items.Add(dr.GetString(0) + " " + dr.GetString(1));
}
}
cnn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
refresh();
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex > -1)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT OgrenciFirstName,OgrenciLastName FROM ogrenciler WHERE OgrenciID = @mynumber", cnn);
cmd.Parameters.AddWithValue("@mynumber", (ListBox1.SelectedIndex + 1));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
TextBox1.Text = dr.GetString(0);
TextBox2.Text = dr.GetString(1);
}
}
cnn.Close();
}
}
page\加载在selectedIndex更改之前运行的代码,并导致dropdownlist selectedIndex=-1
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
refresh();
}
}