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