Hold On
Hold On

Reputation: 19

Binding the result from dropdown list to a textbox in ASP.NET web form

I'm a novice in programming and learning only from video tutorials. I have a created a report card program in ASP.NET web form using C#. In my Web Form, I want a drop down list that will show the names of the students from the database and a text box that supposed to show the students corresponding ID #. I was able to manage to show the list of students in the drop down list from the database. Now, my problem is how can I automatically show the student ID # when the student name is selected from the drop down list? I really appreciate if you can show me a step-by-step process.

Upvotes: 0

Views: 6045

Answers (1)

sgaston
sgaston

Reputation: 26

Add DropDownList and TextBox to your Default.aspx. In the dropdownlist we will store the student name and student id by using DataTextField and DataValueField properties from DropDownList Control. It will get mapped later when we bind the data.

    <div class="jumbotron">
        <h1>Student Report Card Application</h1>
        <p>&nbsp;</p>
        <p>
           Select a Student:
           <asp:DropDownList ID="ddl_StudentName" AutoPostBack="true" DataTextField="student_name" DataValueField="student_id" runat="server">

           </asp:DropDownList>
           &nbsp;&nbsp;&nbsp; <asp:TextBox ID="Student_ID" AutoPostBack="true" runat="server" MaxLength="40"></asp:TextBox>

        </p>
    </div>
    <div class="row">
    </div>

</asp:Content>

Next we need to add some code behind to handle the retrieve of the data. Via Default.aspx.cs code behind. This example will be connecting to a SqlServer Database. Also note whenever we change the dropdown value for the student it will bind the student's id through the onchange event named SelectedIndexChanged. See comments too.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace WebApplication_Test1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //connect to the database now 
            if (Page.IsPostBack == false)
            {
                //we store the database connect information in Web.Config
                //so we retrieve the connection string from the Web.Config
                String mydatabaseconnection = ConfigurationManager.ConnectionStrings["DBConnection"].ToString();
                SqlConnection con = new SqlConnection(mydatabaseconnection);
                //select all records from the grades table via
                //here you can replace this table 'Grades' with your table's schema  
                String myquery = "Select * From Grades";
                SqlCommand command = new SqlCommand(myquery);
                command.CommandType = System.Data.CommandType.Text;
                command.Connection = con;
                try
                {
                    //open the connection to the database 
                    con.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);

                    DataSet ds = new DataSet("Grades");

                    //populate the data into a DataSet 
                    adapter.Fill(ds);

                    //ddl_StudentName.DataSource = ds.Tables[0];
                    ddl_StudentName.DataSource = ds;
                    ddl_StudentName.DataBind(); // bind the data from the table now 
                                                // this is were DataTextField and DataValueField will get mapped
                                                // to database fields student_name and student_id

                    //to handle the drop down change use event SelectedIndexChanged
                    ddl_StudentName.SelectedIndexChanged += Ddl_StudentName_SelectedIndexChanged;

                    //gets the first student from the database and populate the textbox
                    Student_ID.Text = ds.Tables[0].Rows[0]["student_id"].ToString();

                    //close connection to database 
                    con.Close();
                }
                catch (Exception ex)
                {

                }
            }else
            {
                ddl_StudentName.SelectedIndexChanged += Ddl_StudentName_SelectedIndexChanged
            }
        }

        private void Ddl_StudentName_SelectedIndexChanged(object sender, EventArgs e)
        {
            //when we change the dropdownlist we need to get the student id and set it to the textbox
            DropDownList mydropdownlist = sender as DropDownList;
            Student_ID.Text = mydropdownlist.SelectedValue;

        }
    }
}

Sample Web.config Snippet. Here you can see the connection string parameters server=DESKTOP-CPJ3R2K23\SQLEXPRESS,database=UniversityDB, username=sa, password=test1 and the provider is SqlClient. This is needed to connect to the SqlServer Express database in this example.

 <connectionStrings>
  <add name="DBConnection" connectionString="server=DESKTOP-CPJ3R2K23\SQLEXPRESS;database=UniversityDB;Integrated Security=True;uid=sa;pwd=test1"  providerName="System.Data.SqlClient"/> 
 </connectionStrings>

Sample table's scheme from the UniversityDB database.

USE [UniversityDB]
GO

CREATE TABLE [dbo].[Grades](
    [grade] [varchar](10) NULL,
    [student_id] [int] NULL,
    [student_name] [varchar](40) NULL
) ON [PRIMARY]

Hope this helps.

Upvotes: 1

Related Questions