views:

132

answers:

1

As my gridview is populating I want to add an extra column with some buttons in but I can't seem to figure out how, or what might be the best way. Can anyone get me started?

+2  A: 

Use a Template Column

<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1"
    OnRowCommand="GridView1_OnRowCommand">
    <Columns>
        <asp:BoundField DataField="name" HeaderText="Name" />
        <asp:BoundField DataField="email" HeaderText="Email" />
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail"
                    Text="SendMail" CommandArgument='<%# Eval("id") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "SendMail") return;
    int id = Convert.ToInt32(e.CommandArgument);
    // do something
}
Arthur
Awesome thanks! Do you know how to add the command buttons depending on what results come back in the gridview?
SLC
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail" Text="SendMail" CommandArgument='<%# Eval("id") %>' Visible='<%# !string.IsNullOrEmpty(Eval("email") %>)' />
Arthur
For example if it were an e-mail client, you'd have statuses like flagged, unread, etc. so I would want buttons like unflag, mark as read or flag, mark as unread etc. depending on the status. I assume I just add them programmatically, I just wonder which method to do this and how to access that particular cell... I suspect I might have figured out the answer just typing this though :)
SLC
Just add other Buttons to the Template Field. <asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:Button ID="Button1" runat="server" ... /> <asp:Button ID="Button2" runat="server" ... /> <asp:Button ID="Button3" runat="server" ... /> </ItemTemplate> </asp:TemplateField>
Arthur
But not every row has the same buttons, for exampleMessage | Unread - [Mark as Read] [Delete]Message | Unread - [Mark as Read] [Delete]Message | Read - [Mark as Unread] [Delete]Message(!) | Read - [Mark as Unread] [Delete] [Remove Flag]Message | Unread - [Mark as Read] [Delete]The buttons are dynamically created depending on the content, so I can't put them in code
SLC
Ugh that was horribly formatted, basically some rows will have different buttons to others, so I can't put them in code, I must do them programatically, the question is where.
SLC
Just toggle Visiblility: Visible='<%# Eval("CanDelete") %>'
Arthur
Thanks, I figured out how to do it programatically in the databound eventhandler ;D
SLC