Implementation effect: Select a row in the main table and get the details of the row from the table.
Method 1: Code implementation.
Put a GridView and a DetailView on the page. Bind the data to the GridView and set the primary key, and then write code in the SelectedIndexChanged event: when the selection changes, the DetailView also changes to the corresponding Detail.
Specific code:
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>
/// Execute the SQL statement to return a data table
/// </summary>
/// <param name="SQL">SQL statement to be executed</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;
}
}
Method 2: Set the control properties to place a GridView and a DetailView on the page, and then each corresponds to a data source. This can be achieved as long as you use the SelectedValue of the GridView as a parameter in the SelectCommand of the DetailView's data source.
<SelectParameters>
<asp:ControlParameter ControlID="EmployeesGridView" Name="AddressID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
Both methods are very simple, method 2 is basically code-free, and method 1 has more flexible control.