Reputation: 4779
I'd like to add a special row at the bottom of <asp:GridView>
. The template of this row is different from the rows above. How can I make this?
Upvotes: 1
Views: 342
Reputation: 4779
Thanks to @Alan and @lzzy. I made it using <FooterTemplate>
.
<!-- ASPX -->
<asp:GridView ID="UserGridView" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True" OnRowDeleting="UserGridView_OnRowDeleting"
OnRowCommand="UserGridView_OnRowCommand" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="Username" ItemStyle-Width="70">
<ItemTemplate><asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'/> </ItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="NewUsername"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender" ItemStyle-Width="70">
<ItemTemplate><asp:Label ID="Gender" runat="server" Text='<%# Bind("Gender") %>'/></ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewGender" runat="server" >
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Delete" CommandName="Delete"/>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="AddUserButton" runat="server" Text="Add" CommandName="Add"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// CSS
protected void UserGridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add")
{
TextBox newUsername = (TextBox) UserGridView.FooterRow.FindControl("NewUsername");
DropDownList newGender = (DropDownList)UserGridView.FooterRow.FindControl("NewGender");
AddUser(newGender.SelectedValue, newUsername.Text);
BindUserData();
}
}
protected void UserGridView_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
string username = e.Values["Username"].ToString();
string gender = e.Values["Gender"].ToString();
DeleteUser(gender, username);
BindUserData();
}
Some other problem I met along the way and keys to them. In case someone need them.
How to bind data to <asp:Label>
?
Use <%# Bind("DataFieldName") %>
.
Example:
<ItemTemplate><asp:Label ID="Username" runat="server" Text='<%# Bind("Username") %>'/> </ItemTemplate>
Why isn't the footer showing?
Set ShowFooter="true"
in <asp:GridView>
.
How to get the reference to controls in footer?
Example:
TextBox newUsername = (TextBox)UserGridView.FooterRow.FindControl("NewUsername");
How to bind the AddUserButton as the default button?
Example:
MainForm.DefaultButton = UserGridView.FooterRow.FindControl("AddUserButton").UniqueID;
Upvotes: 2
Reputation: 262
You could use the footer template if you always want your 'add' row to be at the bottom of the table:
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:TemplateField>
Upvotes: 2