asp.net中求GridView与DetailView的结合使用方法
asp.net中GridView与DetailView都要是后台绑定数据,且是用带参存储过程去绑定数据的。实现主从表的效果,gridview只显示ID,名称和类别,当选中某行时detailview显示该行的详细信息,求大神帮忙 asp.net gridview 数据 存储 detailview
[解决办法]
何必用DetailView呢,直接在TemplateField显示详细信息不就行了,例如
<asp:GridView runat="server" ID="gv" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="ID" />
<asp:TemplateField HeaderText="个人信息">
<ItemTemplate>
<p>名:<%# Eval("FirstName") %></p>
<p>姓:<%# Eval("LastName") %></p>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView runat="server" ID="gv" AutoGenerateColumns="false"
OnRowCommand="OnSelected" DataKeyNames="EmployeeID">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="select" Text="select" />
<asp:BoundField DataField="EmployeeID" />
<asp:BoundField DataField="LastName" />
</Columns>
</asp:GridView>
<br />
<asp:DetailsView runat="server" ID="dv">
</asp:DetailsView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strConn = WebConfigurationManager.ConnectionStrings["Northwind"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "select * from Employees";
DataTable dt = new DataTable();
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
dt.Load(reader);
gv.DataSource = dt;
gv.DataBind();
reader.Close();
}
finally
{
conn.Close();
}
}
}
protected void OnSelected(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
int i = int.Parse(e.CommandArgument.ToString());
string strID = gv.DataKeys[i].Value.ToString();
string strConn = WebConfigurationManager.ConnectionStrings["Northwind"].ToString();
SqlConnection conn = new SqlConnection(strConn);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "select * from Employees where EmployeeID=" + strID;
DataTable dt = new DataTable();
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
dt.Load(reader);
dv.DataSource = dt;
dv.DataBind();
reader.Close();
}
finally
{
conn.Close();
}
}
}