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
2009-09-28 09:07:57
Awesome thanks! Do you know how to add the command buttons depending on what results come back in the gridview?
SLC
2009-09-28 09:14:41
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail" Text="SendMail" CommandArgument='<%# Eval("id") %>' Visible='<%# !string.IsNullOrEmpty(Eval("email") %>)' />
Arthur
2009-09-28 09:22:05
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
2009-09-28 09:25:26
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
2009-09-28 09:29:06
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
2009-09-28 09:35:28
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
2009-09-28 09:36:01
Just toggle Visiblility: Visible='<%# Eval("CanDelete") %>'
Arthur
2009-09-28 09:48:24
Thanks, I figured out how to do it programatically in the databound eventhandler ;D
SLC
2009-09-28 09:58:33