简体   繁体   English

如果我将列表框刷新方法移入页面加载,则listboxselectedindex停止工作

[英]if I move listbox refresh method into page load, listboxselectedindex stops working

I'm using ASP.NET, I have one refresh button. 我正在使用ASP.NET,我只有一个刷新按钮。 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. 在.cs方面,我有一个方法,它清除列表框并刷新列表框,如果我将其放入页面加载中,则列表框selectedindexchanged事件停止工作。 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();
        }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM