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控制更灵活。