1

I'm using ASP.NET, I have one refresh button. one listbox. two textboxes. on .cs side, I have a method, which clears the listbox and refreshes the listbox, if I put it into page load, the listbox selectedindexchanged event stops working. Why is this?

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();
        }

    }
4

1 回答 1

0
protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      refresh();
   }
}
于 2013-09-05T23:21:58.937 回答