我认为最好的方法是使用UpdatePanel
绑定第二个网格,使用它你会有一个优势,没有回发(实际上是回发,但用户不会注意到它......)......
而如果你不使用UpdatePanel
,那么在回发中绑定后就无法看到数据(除非你是通过Javascript来做的,这很麻烦)......这是实现它的示例代码:
ASPX 页面:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView2" runat="server" >
<Columns>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:LinkButton ID="asd" Text='Select' runat="server" OnClick="link_click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
代码背后:
protected override void PageLoad(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = getDataSource();
GridView1.DataBind();
}
}
private DataTable getDataSource()
{
SqlConnection conn = new SqlConnection("Server=192.168.1.1;DATABASE=dummy;UID=****;PWD=*****;"); //Example connString
SqlCommand comm = new SqlCommand("SELECT * FROM Table1", conn);
SqlDataAdapter ad = new SqlDataAdapter(comm);
DataTable ta = new DataTable();
ad.Fill(ta);
return ta;
}
protected void button_click(object sender, EventArgs e)
{
LinkButton asd = (LinkButton)sender;
GridViewRow row = (GridViewRow)asd.NamingContainer; //Gets the selected Row
string user_id = row.Cells[2].Text; //Use this to get any value you want.
//Can now use the user_name to get the data for the grid 2, and update the panel
GridView2.DataSource = getDataSource2(user_id);
GridView2.DataBind();
UpdatePanel1.Update();
}
private DataTable getDataSource2(string user_id)
{
string sql = "SELECT * FROM TABLE2 WHERE user_id = @user_id";
SqlConnection conn = new SqlConnection("Server=sqlserver\\sql2008;DATABASE=esm80;UID=sa;PWD=sa;"); //Example connString
SqlCommand comm = new SqlCommand();
comm.CommandText = sql;
comm.Parameters.AddWithValue("@name", user_id);
comm.Connection = conn;
SqlDataAdapter ad = new SqlDataAdapter(comm);
DataTable ta = new DataTable();
ad.Fill(ta);
return ta;
}
现在解释一下UpdatePanel
,一旦数据绑定到它,GridView2 就会更新 gridView2(这将显示新绑定的数据)。GridView1的UpdatePanel
存在是为了防止来自链接按钮的回发。
希望这能回答你的问题。