asp.net2.0實現主從資料表的簡單方法

來源:互聯網
上載者:User
asp.net|資料

實現效果:在主表裡選中某行,從表裡得出該行的詳情。

方法1:代碼實現。
在頁面上放一個GridView,一個DetailView。資料繫結GridView並且要設定主鍵,然後在SelectedIndexChanged事件寫代碼:選擇發生變化時,DetailView也改變為相應的Detail。
具體代碼:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


public partial class MasterDetail2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string SQL = "SELECT * FROM [Orders]";
            GridView1.DataSource = Binding(SQL);
            GridView1.DataKeyNames = new string[] { "OrderID" };
            GridView1.DataBind();
        }
     }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string OrderID = Convert.ToString(GridView1.SelectedValue);
        string SQL =  "SELECT * FROM [OrderDetails] WHERE [OrderID]='" + OrderID + "'";
        DetailsView1.DataSource = Binding(SQL);
        DetailsView1.DataBind();
    }


    /**//// <summary>
    /// 執行SQL語句返回一個資料表
    /// </summary>
    /// <param name="SQL">所要執行的SQL語句</param>
    /// <returns>DataTable</returns>
    protected DataTable Binding(string SQL)
    {
        SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString);
        DataTable dt=new DataTable();
        SqlDataAdapter myAdapter = new SqlDataAdapter(SQL, myConn);
        myAdapter.Fill(dt);
        return dt;

    }
}
方法2:設定控制項屬性實現
在頁面上放一個GridView,一個DetailView,然後每個對應一個資料來源。只要在DetailView的資料來源的SelectCommand裡使用GridView的SelectedValue作為參數,即可實現。
            <SelectParameters>
                <asp:ControlParameter ControlID="EmployeesGridView" Name="AddressID" PropertyName="SelectedValue"
                    Type="Int32" />
            </SelectParameters>
兩種方法都很簡單,方法2基本無代碼實現,方法1控制更靈活。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.