简体   繁体   中英

GridView and DetailsView Code Behind to Update DetailsView

I've spent all afternoon trying to do this using CODE BEHIND without success so I am asking for some C# code.

Basically, I have a GV and a DV in a master/detail relationship. GV displays ID and Name. If I click Select on a GV row, I want to see its ID, Name and Address in DV. I know how get this to work declaratively in an aspx file. But in C# code behind, I don't know how to proceed at this function:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Select"))
    {

    //  PLEASE GIVE ME THE CODE HERE TO BIND THE DETAILSVIEW. THANKS!
    // I am using a sqldatasource if it makes any difference

    }
 }

Here's a general solution showing you how to achieve this, please note that this solution isn't extremely error-safe but I suppose you'll get the jist of it. Please comment if there's anything unclear.

Code-behind:

protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
        GridViewRow selected = gv.Rows[Convert.ToInt32(e.CommandArgument)];
        List<ThatClass> cList = new List<ThatClass>();
        cList.Add(new ThatClass(selected.Cells[0].Text, selected.Cells[1].Text));
        dv.DataSource = cList;
        dv.DataBind();
    }
}

Markup:

<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" OnRowCommand="gv_RowCommand">
    <Columns>
        <asp:BoundField DataField="A" HeaderText="A"/>
        <asp:BoundField DataField="B" HeaderText="B" />
        <asp:CommandField ShowSelectButton="true" />
    </Columns>
</asp:GridView>

<asp:DetailsView runat="server" ID="dv">
</asp:DetailsView>

FYI: I bound the GV using a List:

protected void Page_Load(object sender, EventArgs e)
{
    List<ThatClass> cList = new List<ThatClass>();
    cList.Add(new ThatClass("123", "abc"));
    cList.Add(new ThatClass("456", "def"));
    gv.DataSource = cList;
    gv.DataBind();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM