简体   繁体   中英

Fetch data from Database and show in TextBox

在此处输入图片说明 I have a table from where I want to fetch data and show in the TextBox the data are StudentFirstName and SchoolID along with them I need two empty TextBoxes next to them am not sure how to do that.

My data base table

StudentFirstName    SchoolID      StudCourse
abc                  sc123         Bcom
cef                  sc155         Bcom
gij                  sc133         Bcom
abc                  sc122         BCA
cef                  sc156         BCA
gij                  sc144         BCA

C#

using (MySqlConnection myConnection = new MySqlConnection(constr))
{
     string oString = "Select * from euser_student WHERE  StudCourse=@StudCourse order by StudentFirstName  ASC";
     MySqlCommand oCmd = new MySqlCommand(oString, myConnection);

     oCmd.Parameters.AddWithValue("@StudCourse", StudCourse);   
     myConnection.Open();
     using (MySqlDataReader oReader = oCmd.ExecuteReader())
     {
          if (oReader == null || !oReader.HasRows)
          {
               ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);
          }
          else
          {
              while (oReader.Read())
              { 

              }
          }
          myConnection.Close();
     }               
}

You can use SqlDataReader.GetString Method to get the value of the specified column as a string Like this:

while (oReader.Read())
{
    TextBox1.Text = oReader.GetString(1); // 1 is the Parameter that is The zero-based column ordinal you can change it to what you want
    TextBox2.Text = oReader.GetString(2);
}

Check this to learn more : Retrieving Data Using a DataReader .

But If you want to show more than one row it would be better if you use a GridView control to show data. First add a GridView to your aspx like this:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

And then:

GridView1.DataSource = oReader;
GridView1.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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