如果我在页面加载时移动列表框刷新方法,listbox selectedindex将停止工作

时间:2013-09-05 23:19:41

标签: 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.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();
        }

    }

1 个答案:

答案 0 :(得分:0)

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      refresh();
   }
}