2.17. Inserting a Row Within a GridView
Problem
You want to provide the ability for a user to insert a new row of data within a GridView
.
Solution
Add a GridView
and an updateable data source, such as an asp:SqlDataSource
, to the .aspx file, set the ShowFooter
attribute of the GridView
control to true
, add Footer-Template
elements for each column that is to be inserted, add an Insert button in the footer, and initialize the properties of the data source in the code-behind. When the user clicks the Insert button, set the parameter values from the entered data and use the data source to insert the data in the GridView's RowCommand
event handler in the code-behind.
In the .aspx file:
Add a
GridView
control where the data is to be displayed.Add an
asp:SqlDataSource
.Set the
ShowFooter
attribute of theGridView
totrue
.Add
FooterTemplate
elements for each column that is to be inserted.
In the Page_Init
event handler of the code-behind class for the page, use the .NET language of your choice to:
Initialize the
SelectCommand
property of theSqlDataSource
to the SQL statement used to get the data to display from the database.Initialize the
InsertCommand
property of theSqlDataSource
to the SQL statement (with parameters) used to insert in the database the data the user enters.Add the parameters for the data the user can update to the
InsertParameters
collection of theSqlDataSource
.In the
RowCommand
event handler, set the values of theInsertParameters
of theSqlDataSource
from the controls containing ...
Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.