2016-03-20 15 views
0

私はビデオチュートリアルからのプログラミングと学習の初心者です。私はC#を使用してASP.NET Webフォームで作成されたレポートカードプログラムを持っています。私のWebフォームでは、データベースから生徒の名前を表示するドロップダウンリストと、生徒に対応するID番号を示すテキストボックスが必要です。私はデータベースからドロップダウンリストに生徒のリストを表示することができました。今、私の問題は、生徒の名前がドロップダウンリストから選択されたときに、生徒のID番号を自動的に表示する方法です。あなたが私に段階的なプロセスを示すことができれば本当にありがたいです。ドロップダウンリストの結果をASP.NET Webフォームのテキストボックスにバインドします

+1

ようこそスタックオーバーフロー。 Stack Overflowの[質問のヘルプ](http://stackoverflow.com/help/asking)をまずチェックしてください。 [どのトピックを私がここで尋ねることができます](http://stackoverflow.com/help/on-topic)、[どのような種類の質問を避けるべきですか?](http://stackoverflow.com/help/dont)に注目してください。 )、[最小限で完全で検証可能なサンプルの作成方法](http:// stackoverflow。 com/help/mcve)と[Stack Overflow question checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)を参照してください。 –

答えて

1

Default.aspxにDropDownListとTextBoxを追加します。 DropDownListコントロールのDataTextFieldプロパティとDataValueFieldプロパティを使用して、学生名と学生IDをドロップダウンリストに格納します。後でデータをバインドするときにマップされます。

<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> 

次はデータの取得処理するための背後にあるいくつかのコードを追加する必要があります。 Default.aspx.csコードを使用してください。この例では、SqlServerデータベースに接続します。また、学生のドロップダウン値を変更するたびに、SelectedIndexChangedという名前のonchangeイベントを通じて学生のIDがバインドされます。コメントも参照してください。

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; 

     } 
    } 
} 

サンプルWeb.configスニペット。接続文字列パラメータ server = DESKTOP-CPJ3R2K23 \ SQLEXPRESS、database =大学DB、ユーザー名= sa、パスワード= test1、プロバイダーはSqlClientです。この例では、SqlServer Expressデータベースに接続するために必要です。 UniversityDBデータベースから

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

サンプルテーブルのスキーム。

USE [UniversityDB] 
GO 

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

希望します。

関連する問題