How to display data from database into textbox, and update it

后端 未结 4 1913
难免孤独
难免孤独 2020-12-15 02:08

I can display my data in my textbox, dropdownlist after retrieve data from sql database, but when i proceed with my update button, the information edited in the textbox or d

4条回答
  •  失恋的感觉
    2020-12-15 02:27

    The answer is .IsPostBack as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

    private void PopulateFields()
    {
      using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
      {
        DataTable dt = new DataTable();
        con1.Open();
        SqlDataReader myReader = null;  
        SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
    
        myReader = myCommand.ExecuteReader();
    
        while (myReader.Read())
        {
            TextBoxPassword.Text = (myReader["password"].ToString());
            TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
            DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
            DropDownListMonth.Text = (myReader["birth"].ToString());
            DropDownListYear.Text = (myReader["birth"].ToString());
            TextBoxAddress.Text = (myReader["address"].ToString());
            TextBoxCity.Text = (myReader["city"].ToString());
            DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
            TextBoxPostcode.Text = (myReader["postcode"].ToString());
            TextBoxEmail.Text = (myReader["email"].ToString());
            TextBoxCarno.Text = (myReader["carno"].ToString());
        }
        con1.Close();
      }//end using
    }
    

    Then call it in your Page_Load

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

提交回复
热议问题