I have this page with a GridView control inside that's bound to database. GridView has a command row for insert, delete and updating. The problem is that, since my database table is initially empty, I see an empty grid. I don't even see the command row in order to be able to insert anything into it.
I managed to solve this by checking for GridView row cou开发者_JS百科nt and changing its display to InsertTemplate. But I'm wondering if there's a standard way of doing this, may it already has such functionality? The same problem with DetailView. ThanksYou can use the EmptyDataTemplate to handle inserting a new item if the grid's data source is initially empty.
Define your grid in the ASPX as follows:
<asp:GridView runat="server" ID="grid" AutoGenerateColumns="false"
OnRowCommand="grid_RowCommand">
<Columns>
<asp:ButtonField ButtonType="Link" CommandName="Add" Text="Add" />
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
</Columns>
<EmptyDataTemplate>
<asp:TextBox ID="CustomerFirstName" runat="server"></asp:TextBox><br />
<asp:TextBox ID="CustomerLastName" runat="server"></asp:TextBox><br />
<asp:Button ID="Save" Text="Save" runat="server" CommandName="EmptyAdd"
UseSubmitBehavior="False" />
</EmptyDataTemplate>
</asp:GridView>
A collection of Customer objects is used as the datasource for the grid.
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Bind the grid to a data source (empty for this example).
protected void Page_Load(object sender, EventArgs e)
{
var customers = new List<Customer> {};
grid.DataSource = customers;
grid.DataBind();
}
You can then handle the Add and EmptyAdd command in the grid_RowCommand event handler.
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EmptyInsert")
{
}
if (e.CommandName == "Insert")
{
}
}
精彩评论