开发者

GridView and DetailsView Code Behind to Update DetailsView

开发者 https://www.devze.com 2023-03-12 10:57 出处:网络
I\'ve spent all afternoon trying to do this using CODE BEHIND without success so I am asking for some C# code.

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_RowComm开发者_运维百科and(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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消