点击GridView某一行的按钮,在另一个GridView中显示该条信息的详细信息
两种方法:
1.前台不采用模板列:
GridView1中
<asp:ButtonField Text="查看" ButtonType="Button" commandName="look" HeaderStyle-HorizontalAlign ="Center" Itemstyle-HorizontalAlign="Center" />
对应后台代码:差别就在前两行
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//显示订单从表信息
if (e.CommandName.ToString() == "look")
{
int index = Convert.ToInt32(e.CommandArgument.ToString());//得到行号
string sql2 = "select * from tb_orderDetails where orderID='" + GridView1.DataKeys[index].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(sql2, con.conn);
SqlDataAdapter da = new SqlDataAdapter();
con.OpenConn();
da.SelectCommand = cmd;
con.CloseConn();
DataSet ds = new DataSet();
da.Fill(ds, "details");
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
string strID = e.CommandArgument.ToString();
string sql2 = "select * from tb_orderDetails where orderID='" + strID + "'";
SqlCommand cmd = new SqlCommand(sql2, con.conn);
SqlDataAdapter da = new SqlDataAdapter();
con.OpenConn();
da.SelectCommand = cmd;
con.CloseConn();
DataSet ds = new DataSet();
da.Fill(ds, "details");
GridView2.DataSource = ds;
GridView2.DataBind();
2.前台采用模板列
GridView1中
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="look" Text="查看" CommandArgument='<%#Eval("orderID") %>'></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
对应后台代码:差别就在前两行
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//显示订单从表信息
if (e.CommandName.ToString() == "look")
{
string strID = e.CommandArgument.ToString();
string sql2 = "select * from tb_orderDetails where orderID='" + strID + "'";
SqlCommand cmd = new SqlCommand(sql2, con.conn);
SqlDataAdapter da = new SqlDataAdapter();
con.OpenConn();
da.SelectCommand = cmd;
con.CloseConn();
DataSet ds = new DataSet();
da.Fill(ds, "details");
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
为什么写法会这样?自己调试的时候发现,两种形式下,e.CommandArgument里的存储的值不同
第一个,存的是当前行索引值
第二个,存的是当前行主键的值