實現效果:在主表裡選取某行,從表裡得出該行的詳情。
方法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控制更靈活。