Home>

This article describes how to dynamically insert a new row in the footer of the gridview in asp.net 2.0.To display the footer line, just set the showfooter property to true. We can customize the footer row by converting each column into a templatefield and customizing the insertion interface in its footertemplate template.

preface:

As the tutorial "Overview of inserting, updating, and deleting dataAs discussed in The gridview, detailsview and formview web controls all have built-in data modification capabilities.When a declaration is bound to a data source control,You can modify data quickly and easily-without even writing a single line of code.Unfortunately,Only the detailsview and formview controls provide built-in insert, edit, and delete functions.The gridview control only supports editing and deleting functions.However, with a little effort,We can make the gridview control include an insert interface.

In order to add insert function to gridview,We have to decide how to add new records:create an insert interface,Encode the inserted data.In this tutorial,We will add an insert interface to the footer row of the gridview (see Figure 1). Each column contains the corresponding user interface elements (such as entering a product name in a textbox,Select suppliers in dropdownlis, etc.) At the same time, we need an "add" button. When clicked,A page postback occurred,Add the new record to the products table.

Figure 1:The footer line provides an interface for adding new records

Step 1:Display product information in the gridview control

First add a gridview control to display the product. Open the insertthroughfooter.aspx page in the enhancedgridview folder, add a gridview control to it, set its id to products, and then bind it to an objectdatasource named productsdatasource in its smart tag.

Figure 2:Create a new objectdatasource named productsdatasource

Set the objectdatasource to call the getproducts () method of the productsbll class to obtain product information.In this tutorial,We only focus on adding insert functionality,It has nothing to do with editing and deleting.So, make sure to select the addproduct () method in the "Insert" tab. Select "(none)" in "Edit" and "Delete".

Figure 3:Set the insert () method of objectdatasource to addproduct ()

Figure 4:Select "(none)" in the update and delete options

After setting up,Visual Studio will automatically add related columns.Now, we don't care about these columns for now,Later in the tutorial,We will remove some columns,Because we do not need to specify the values ​​of these columns when adding new records.

Because there are about 80 products in the database, we better enable the paging function.In order to make the insertion interface more intuitive and easier to operate.Back on the page,Enable pagination in gridview's smart tags.

The gridview and objectdatasource declaration code now looks similar to the following:

<asp:gridview runat="server" autogeneratecolumns="false"
 datakeynames="productid" datasourceid="productsdatasource"
 allowpaging="true" enableviewstate="false">
 <columns>
 <asp:boundfield datafield="productid" headertext="productid"
  insertvisible="false" readonly="true"
  sortexpression="productid" />
 <asp:boundfield datafield="productname" headertext="productname"
  sortexpression="productname" />
 <asp:boundfield datafield="supplierid" headertext="supplierid"
  sortexpression="supplierid" />
 <asp:boundfield datafield="categoryid" headertext="categoryid"
  sortexpression="categoryid" />
 <asp:boundfield datafield="quantityperunit" headertext="quantityperunit"
  sortexpression="quantityperunit" />
 <asp:boundfield datafield="unitprice" headertext="unitprice"
  sortexpression="unitprice" />
 <asp:boundfield datafield="unitsinstock" headertext="unitsinstock"
  sortexpression="unitsinstock" />
 <asp:boundfield datafield="unitsonorder" headertext="unitsonorder"
  sortexpression="unitsonorder" />
 <asp:boundfield datafield="reorderlevel" headertext="reorderlevel"
  sortexpression="reorderlevel" />
 <asp:checkboxfield datafield="discontinued" headertext="discontinued"
  sortexpression="discontinued" />
 <asp:boundfield datafield="categoryname" headertext="categoryname"
  readonly="true" sortexpression="categoryname" />
 <asp:boundfield datafield="suppliername" headertext="suppliername"
  readonly="true" sortexpression="suppliername" />
 </columns>
</asp:gridview>
<asp:objectdatasource runat="server"
 insertmethod="addproduct" oldvaluesparameterformatstring="original_ {0}"
 selectmethod="getproducts" typename="productsbll">
 <insertparameters>
 <asp:parameter name="productname" type="string" />
 <asp:parameter name="supplierid" type="int32" />
 <asp:parameter name="categoryid" type="int32" />
 <asp:parameter name="quantityperunit" type="string" />
 <asp:parameter name="unitprice" type="decimal" />
 <asp:parameter name="unitsinstock" type="int16" />
 <asp:parameter name="unitsonorder" type="int16" />
 <asp:parameter name="reorderlevel" type="int16" />
 <asp:parameter name="discontinued" type="boolean" />
 </insertparameters>
</asp:objectdatasource>

Figure 5:In a gridview with pagination enabled, all data items of the product are displayed

Step 2:Add a footer line

The gridview control contains a header row, a data row, and a footer row.The showheader and showfooter properties of the gridview control determine whether the header and footer rows are displayed.If i want to display the footer line,We need to set the showfooter property to true. As shown in Figure 6:

Figure 6:Set the showfooter property to true and add a footer line

We noticed that the background color of the footer row is dark red,This is due to ourPresenting data using objectdatasource》 Created a theme named datawebcontrols and applied it to all page backgrounds.In particular, the skin file gridview.skin sets the footerstyle property to use footerstyle css, and its code is as follows:

.footerstyle
{
 background-color:#a33;
 color:white;
 text-align:right;
}

Note:In the previous tutorial we mentioned using the footer line of the gridview.If not clear,Please refer to Chapter 15 of the tutorialShow statistics in footer of gridview》

After setting the showfooter property to true, watch the effect in the browser.The current footer line does not contain any text or web controls. In step 3, we will modify it to include the corresponding insert interface.

Figure 7:The footer line appears blank

Step 3:Customize the footer line

Review the tutorial "Use templatefield in gridview control》, In that tutorial we explored how to use templatefields (instead of boundfields or checkboxfields) on a column of the gridview to achieve custom display stylesAnd in the tutorial "Custom data modification interfaceIn》 we saw how to use templatefields to customize the editing interface in gridview.A templatefield is composed of templates such as itemtemplate and edititemtemplate.For example, the data displayed by the itemtemplate template is read-only;The edititemtemplate template customizes an edit line interface.

In addition to templates such as itemtemplate and edititemtemplate,templatefield also contains a template called footertemplate, which specifies a footer line for the container.So we can add web controls to the footertemplate template to insert the interface. let's start,First, we convert all columns in the gridview control into templatefields. Click "Edit Columns" in the smart tab of the gridview control, and select each field on the left.Then click "convert this field into a templatefield".

Figure 8:Converting each field to a templatefield

Click "convert this field into a templatefield" to convert the field of the current type into the corresponding templatefield. For example, each boundfield will be converted into a templatefield whose itemtemplate contains a label control to display the corresponding data field;Its edititemtemplate uses a textbox control to display the corresponding data fields.For example, here a boundfield named productname will be converted to a templatefield like this:

<asp:templatefield headertext="productname" sortexpression="productname">
 <edititemtemplate>
 <asp:textbox runat="server"
  text="<%#bind (" productname ")%>"></asp:textbox>
 </edititemtemplate>
 <itemtemplate>
 <asp:label runat="server"
  text="&%;bind (" productname ")%>"</asp:label>
 </itemtemplate>
</asp:templatefield>

Similarly, after the checkboxfield named discontinued is converted to templatefield, its itemtemplate and edititemtemplate templates will both contain a checkbox web control (only the checkbox in the itemtemplate template is not available);and the productid boundfield in the "read-only" state is converted to templatefield , Both its itemtemplate and edititemtemplate templates contain a label control. in short,Converting a column in gridview to a templatefield is a quick and easy way to customize custom templates.And will not lose the function that the column should have.

Since we don't need gridview to support editing functions,Delete the edititemtemplate template for each templatefield,Only the itemtemplate template is left. When completed, the gridview code should look similar to the following:

<asp:gridview runat="server" autogeneratecolumns="false"
 datakeynames="productid" datasourceid="productsdatasource"
 allowpaging="true" enableviewstate="false" showfooter="true">
 <columns>
 <asp:templatefield headertext="productid" insertvisible="false"
  sortexpression="productid">
  <itemtemplate>
  <asp:label runat="server"
   text="&%;bind (" productid ")%>"</asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="productname" sortexpression="productname">
  <itemtemplate>
  <asp:label runat="server"
   text="&%;bind (" productname ")%>"</asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="supplierid" sortexpression="supplierid">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" supplierid ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="categoryid" sortexpression="categoryid">
  <itemtemplate>
  <asp:label runat="server"
   text="&%;bind (" categoryid ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="quantityperunit"
  sortexpression="quantityperunit">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" quantityperunit ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="unitprice" sortexpression="unitprice">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitprice ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="unitsinstock"
  sortexpression="unitsinstock">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitsinstock ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="unitsonorder"
  sortexpression="unitsonorder">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitsonorder ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="reorderlevel"
  sortexpression="reorderlevel">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" reorderlevel ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="discontinued"
  sortexpression="discontinued">
  <itemtemplate>
  <asp:checkbox runat="server"
   checked="<%#bind (" discontinued ")%>" enabled="false" />
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="categoryname"
  sortexpression="categoryname">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" categoryname ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 <asp:templatefield headertext="suppliername"
  sortexpression="suppliername">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" suppliername ")%>"></asp:label>
  </itemtemplate>
 </asp:templatefield>
 </columns>
</asp:gridview>

Now that each gridview column has been converted into a templatefield, we add the appropriate insert interface in its footertemplate.However, some columns have no interface (such as productid), and the templatefield template in other columns will contain web controls for users to enter product information.

Click on Click "edit templates" in the smart tag of gridview, select a column of footertemplate template from the drop-down list, and drag an appropriate control from the toolbox to the page.

Figure 9:Add the appropriate insert interface to the footertemplate of each column.

Listed below are all the columns of the gridview,And specify which insert interfaces are added to each column:

productid-None

productname-add a textbox with id newproductname;add another

requiredfieldvalidator control to prevent users from not entering a product name.

supplierid-None

categoryid-none

quantityperunit-add a textbox with id newquantityperunit

unitprice-add a textbox with the id newunitprice, and add a comparevalidator control to ensure that the user enters a currency value,And>= 0

unitsinstock-add a textbox with id newunitsinstock, and add a comparevalidator control to ensure that the user enters an integer value,And>= 0

unitsonorder-add a textbox with id newunitsonorder, and add a comparevalidator control to ensure that the user enters an integer value,And>= 0

reorderlevel-add a textbox with id newreorderlevel, and add a comparevalidator control to ensure that the user enters an integer value,And>= 0

discontinued-add a checkbox with id newdiscontinued

categoryname --- Add a dropdownlist control with the id newcategoryid. Bind it to an objectdatasource control named categoriesdatasource and set it to call the getcategories () method of the categoriesbll class. Set the dropdownlist control to display the categoryname, and set the values ​​of the dropdownlist control to categoryid

suppliername-Add a dropdownlist control with the id newsuplid. Bind it to an objectdatasource control named suppliersdatasource and set it to call the getsuppliers () method of the suppliersbll class. Set the dropdownlist control to display companyname and set the values ​​of the dropdownlist control to supplierid .

Empty the forecolor property of each validation control,In order to replace the default red with the white background color defined in the footerstyle css class;At the same time, set errormessage to detailed error prompts;Set the text property to an asterisk.In each footertemplates, as long as it contains a validation control, set its wrap property to false. Finally, add a validationsummary control under the gridview control, and set the showmessagebox property to true;the showsummary property to false.

When adding a new product,We need to give the categoryid and supplierid values. The two dropdownlist controls on the page show the categoryname and suppliername, but what we pass is what we need

categoryid and supplierid values. Why not display the categoryid and supplierid values ​​directly?Because end users are more interested in categoryname and suppliername.Now that the corresponding categoryid and supplierid values ​​can be obtained in the insert interface displaying categoryname and suppliername, we have removed the templateid and supplierid 2 templatefields from the gridview.

Similarly, we don't need productid when adding new products, so we can also delete the productid templatefield, but here we keep it.In addition to textboxes, dropdownlists,

In addition to checkboxes and validation controls, we need to add an "add" button to the insert interface. When the button is clicked,Add new records to the database.In step 4, we will add an "add" button to the footertemplate template of the productid templatefield.

Improve Improve the way you like.For example, format the unitprice value as currency;Place the unitsinstock, unitsonorder and reorderlevel columns on the right;Modify templatefields' headertext attributes, etc.

carry out After modifying the insertion interface in footertemplates,Remove the supplierid and categoryid templatefields. In the end, the declaration code for your gridview control should look similar to the following:

<asp:gridview runat="server" autogeneratecolumns="false"
 datakeynames="productid" datasourceid="productsdatasource"
 allowpaging="true" enableviewstate="false" showfooter="true">
 <columns>
 <asp:templatefield headertext="productid" insertvisible="false"
  sortexpression="productid">
  <itemtemplate>
  <asp:label runat="server"
   text="&%;bind (" productid ")%>"</asp:label>
  </itemtemplate>
  <itemstyle horizontalalign="center" />
 </asp:templatefield>
 <asp:templatefield headertext="product" sortexpression="productname">
  <itemtemplate>
  <asp:label runat="server"
   text="&%;bind (" productname ")%>"</asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:textbox runat="server"></asp:textbox>
  <asp:requiredfieldvalidator
   runat="server" controltovalidate="newproductname"
   display="dynamic" forecolor=""
   errormessage="you must enter a name for the new product.">
   *</asp:requiredfieldvalidator>
  </footertemplate>
  <footerstyle wrap="false" />
 </asp:templatefield>
 <asp:templatefield headertext="category" sortexpression="categoryname">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" categoryname ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:dropdownlist runat="server"
   datasourceid="categoriesdatasource"
   datatextfield="categoryname" datavaluefield="categoryid">
  </asp:dropdownlist>
  <asp:objectdatasource runat="server"
   oldvaluesparameterformatstring="original_ {0}"
   selectmethod="getcategories" typename="categoriesbll">
  </asp:objectdatasource>
  </footertemplate>
 </asp:templatefield>
 <asp:templatefield headertext="supplier" sortexpression="suppliername">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" suppliername ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:dropdownlist runat="server"
   datasourceid="suppliersdatasource"
   datatextfield="companyname" datavaluefield="supplierid">
  </asp:dropdownlist><asp:objectdatasource
   runat="server" oldvaluesparameterformatstring="original_ {0}"
   selectmethod="getsuppliers" typename="suppliersbll">
  </asp:objectdatasource>
  </footertemplate>
 </asp:templatefield>
 <asp:templatefield headertext="qty/unit" sortexpression="quantityperunit">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" quantityperunit ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:textbox runat="server"></asp:textbox>
  </footertemplate>
 </asp:templatefield>
 <asp:templatefield headertext="price" sortexpression="unitprice">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitprice "," {0:c} ")%>"></asp:label >
  </itemtemplate>
  <footertemplate>
  $<asp:textbox runat="server" columns="8" />
  <asp:comparevalidator runat="server"
   controltovalidate="newunitprice"
   errormessage="you must enter a valid currency value greater than
   or equal to 0.00. do not include the currency symbol. "
   forecolor="" operator="greaterthanequal" type="currency"
   valuetocompare="0" display="dynamic">
   *</asp:comparevalidator>
  </footertemplate>
  <itemstyle horizontalalign="right" />
  <footerstyle wrap="false" />
 </asp:templatefield>
 <asp:templatefield headertext="units in stock"
  sortexpression="units in stock">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitsinstock ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:textbox runat="server" columns="5" />
  <asp:comparevalidator runat="server"
   controltovalidate="newunitsinstock" display="dynamic"
   errormessage="you must enter a valid numeric value for units
   in stock that "s greater than or equal to zero."
   forecolor="" operator="greaterthanequal" type="integer"
   valuetocompare="0"&​​gt;*</asp:comparevalidator>
  </footertemplate>
  <itemstyle horizontalalign="right" />
  <footerstyle wrap="false" />
 </asp:templatefield>
 <asp:templatefield headertext="units on order" sortexpression="unitsonorder">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" unitsonorder ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:textbox runat="server" columns="5" />
  <asp:comparevalidator runat="server"
   controltovalidate="newunitsonorder" display="dynamic"
   errormessage="you must enter a valid numeric value for units on
   order that "s greater than or equal to zero."
   forecolor="" operator="greaterthanequal" type="integer"
   valuetocompare="0"&​​gt;*</asp:comparevalidator>
  </footertemplate>
  <itemstyle horizontalalign="right" />
  <footerstyle wrap="false" />
 </asp:templatefield>
 <asp:templatefield headertext="reorder level" sortexpression="reorderlevel">
  <itemtemplate>
  <asp:label runat="server"
   text="<%#bind (" reorderlevel ")%>"></asp:label>
  </itemtemplate>
  <footertemplate>
  <asp:textbox runat="server" columns="5" />
  <asp:comparevalidator runat="server"
   controltovalidate="newreorderlevel" display="dynamic"
   errormessage="you must enter a valid numeric value for reorder
   level that "s greater than or equal to zero."
   forecolor="" operator="greaterthanequal" type="integer"
   valuetocompare="0"&​​gt;*</asp:comparevalidator>
  </footertemplate>
  <itemstyle horizontalalign="right" />
  <footerstyle wrap="false" />
 </asp:templatefield>
 <asp:templatefield headertext="discontinued" sortexpression="discontinued">
  <itemtemplate>
  <asp:checkbox runat="server"
   checked="<%#bind (" discontinued ")%>" enabled="false" />
  </itemtemplate>
  <footertemplate>
  <asp:checkbox runat="server" />
  </footertemplate>
  <itemstyle horizontalalign="center" />
  <footerstyle horizontalalign="center" />
 </asp:templatefield>
 </columns>
</asp:gridview>

View When viewing this page in a browser,The footer row of the gridview control is displayed as a relatively complete insertion interface (as shown in Figure 10). At this time, the insert interface does not include a method to add the entered data to the database.And we haven't explained how the data entered is converted into a record.In step 4, we will see how to add an "add" button and how to execute the code after the page is passed back.In step 5, we see how to convert the typed data into a record and add it to the database.

Figure 10:The footer row of the gridview provides an interface for adding new records

Step 4:Add the add button in the insert interface

As mentioned before, we need to add an add button to the interface. We can add a button in a footertemplate or another column to achieve this purpose.In this tutorial,We add this button to the footertemplate of the productid templatefield.

Click "Edit Template" in the gridview smart tab, select footertemplate corresponding to productid, add a button web control (linkbutton or imagebutton, as long as you like), set id to addproduct;commandname attribute to insert;text attribute to "add" , As shown in Figure 11:

Figure 11:The footertemplate template with the add button in the productid templatefield

After adding the button,View the page in a browser.If we enter invalid data in the interface,When you click the add button again, the page rotation is interrupted.At the same time, the validationsummary control lists the invalid data in detail (see Figure 12). After entering the appropriate data,Click the button again,Will trigger a page postback,But no records are added to the database.We need to write code to implement the function of inserting data.

Figure 12:If invalid data is entered,Will break the page rotation

Note:The validation controls in the interface are not set as a group.When only the insert interface in the page contains a validation control,No problem running.However, if there are other validation controls in the page (for example, if there is an editing interface,It also contains a validation control), we should set the validation control inserted in the interface and the validationgroup property of the add button to the same value,Make it a specific validation group.

Step 5:Add a new record to the products table

use When using the built-in editing functions of the gridview control,gridview automatically handles the work necessary to edit the product.When clicking the edit button,It copies the data typed in the edit page to the parameters contained in the updateparameters parameter set of objectdatasource,Then call the update () method of the objectdatasource control to perform the update.Since gridview does not provide built-in functionality for inserting data,We must write code to call the insert () method of the objectdatasource control, and copy the data typed in the insert interface to the insertparameters collection of the objectdatasource control.

Like in tutorial 28 "button in gridviewThe same thing is discussed in "Any time,Just click the button, linkbutton or imagebutton in the gridview control, and trigger the gridview's rowcommand event when the page is rotated. Regardless of whether these button, linkbutton, and imagebutton controls are added explicitly (for example, the add button added in the footer row) or are automatically added by the gridview control (for example, when the paging function or sorting function is enabled,The linkbuttons that appear at the top).

Click on Click the add button for the corresponding user, we want to create an event handler for the rowcommand event of the gridview.Since clicking on any button, linkbutton or imagebutton of the gridview control will trigger this event at any time,We must specify when the value of the commandname attribute passed to the event handler is the same as the add button (ie:"insert") and the data entered is correctOnly perform the insert operation.code show as below:

protected void products_rowcommand (object sender, gridviewcommandeventargs e)
{
 //insert data if the commandname == "insert"
 //and the validation controls indicate valid data ...
 if (e.commandname == "insert" &&page.isvalid)
 {
 //todo:insert new record ...
 }
}

Note:you might be wondering why you should check the page.isvalid property?After all, if invalid data is entered in the insert interface,Page postback will be interrupted.The page.isvalid property is checked to prevent situations where the user does not have javascript enabled or cleverly bypasses client-side validation.in short,If no client-side validation is performed,Validation must be performed again on the server side before processing the data.

In step 1, the insert () method of the productsdatasource objectdatasource control maps the addproduct method of the productsbll class. In order to add new records to the table products,We just need to simply call the insert () method of the objectdatasource:

protected void products_rowcommand (object sender, gridviewcommandeventargs e)
{
 //insert data if the commandname == "insert"
 //and the validation controls indicate valid data ...
 if (e.commandname == "insert" &&page.isvalid)
 {
 //insert new record
 productsdatasource.insert ();
 }
}

The insert () method can now be called. The remaining step is to pass the value typed in the insert interface to the parameter in the addproduct method of the productsbll class.Just like in Tutorial 17Study the associated events for inserts, updates, and deletes"It ’s the same thing,Can be achieved through the inserting event of the objectdatasource control.In the inserting event, we need to programmatically access the controls in the footer row.Assign its value to the e.inputparameters collection. When the user ignores a value-such as leaving the reorderlevel text box empty,We should specify the value as null. Because the addproducts method allows nullable columns to receive null values. code show as below:

protected void productsdatasource_inserting
 (object sender, objectdatasourcemethodeventargs e)
{
 //programmatically reference web controls in the inserting interface ...
 textbox newproductname =
 (textbox) products.footerrow.findcontrol ("newproductname");
 dropdownlist newcategoryid =
 (dropdownlist) products.footerrow.findcontrol ("newcategoryid");
 dropdownlist newsupplierid =
 (dropdownlist) products.footerrow.findcontrol ("newsupplierid");
 textbox newquantityperunit =
 (textbox) products.footerrow.findcontrol ("newquantityperunit");
 textbox newunitprice =
 (textbox) products.footerrow.findcontrol ("newunitprice");
 textbox newunitsinstock =
 (textbox) products.footerrow.findcontrol ("newunitsinstock");
 textbox newunitsonorder =
 (textbox) products.footerrow.findcontrol ("newunitsonorder");
 textbox newreorderlevel =
 (textbox) products.footerrow.findcontrol ("newreorderlevel");
 checkbox newdiscontinued =
 (checkbox) products.footerrow.findcontrol ("newdiscontinued");
 //set the objectdatasource "s insertparameters values ​​...
 e.inputparameters ["productname"]=newproductname.text;
 e.inputparameters ["supplierid"] =
 convert.toint32 (newsupplierid.selectedvalue);
 e.inputparameters ["categoryid"] =
 convert.toint32 (newcategoryid.selectedvalue);
 string quantityperunit=null;
 if (! string.isnullorempty (newquantityperunit.text))
 quantityperunit=newquantityperunit.text;
 e.inputparameters ["quantityperunit"]=quantityperunit;
 decimal?unitprice=null;
 if (! string.isnullorempty (newunitprice.text))
 unitprice=convert.todecimal (newunitprice.text);
 e.inputparameters ["unitprice"]=unitprice;
 short?unitsinstock=null;
 if (! string.isnullorempty (newunitsinstock.text))
 unitsinstock=convert.toint16 (newunitsinstock.text);
 e.inputparameters ["unitsinstock"]=unitsinstock;
 short?unitsonorder=null;
 if (! string.isnullorempty (newunitsonorder.text))
 unitsonorder=convert.toint16 (newunitsonorder.text);
 e.inputparameters ["unitsonorder"]=unitsonorder;
 short?reorderlevel=null;
 if (! string.isnullorempty (newreorderlevel.text))
 reorderlevel=convert.toint16 (newreorderlevel.text);
 e.inputparameters ["reorderlevel"]=reorderlevel;
 e.inputparameters ["discontinued"]=newdiscontinued.checked;
}

After adding the inserting event handler,We can add records through the footer row of the gridview control.To get started, try adding a few products.

Optimize and customize the add operation

Generally speaking,After clicking the add button, a new record will be added to the database.However, there is no intuitive indication that the record was successfully added.Indeed, a label web control or client-side message box should be used to inform the user that the product has been successfully added,I leave it to the reader as an exercise.

The gridview control used in this article does not sort the displayed products in any way.Nor does it allow end users to sort the data.As a result, products are sorted by the order in which they appear in the database-by primary key value order.Because the productid value of each newly added record is greater than the value of the previous one,So when adding new records,It naturally ranked last.So when adding a new record,You want to automatically go to the last page of the gridview control.How can this be done?In the rowcommand event handler,After calling the productsdatasource.insert () method, immediately add the following line of code,It states that when data is bound to the gridview, it will go to the last page:

//indicate that the user needs to be sent to the last page
sendusertolastpage=true;

Where sendusertolastpage is a Boolean variable of the page-level,Its initial value is false. In the databound event handler of the gridview control,If sendusertolastpage is false, the pageindex property will take the user to the last page.

protected void products_databound (object sender, eventargs e)
{
 //send user to last page of data, if needed
 if (sendusertolastpage)
 products.pageindex=products.pagecount-1;
}

Why do we set the pageindex property in the databound event handler (instead of the rowcommand event handler)?If you set the pageindex property in rowcommand,It returns the pageindex value before the new record was added. In most instances,This is no problem,However, if the newly added record falls on a new page (translation:for example, there were 80 products originally, divided into 8 pages, the page index of the last page is 7 at this time.The newly added product becomes the first record on page 9,At this time, the page index of the last page is 8 instead of 7 before adding the product. If we use the pageindex value set in the rowcommand, the page will jump to the second last page instead of the last page we expected.The databound event occurs after the product is added and rebind.The pageindex value we set in the databound event handler is the actual pageindex value of the last page.

Finally, the gridview used in this article looks quite wide,Because there are many columns used to add product information.Therefore, it is best to set it up vertically.In addition, we can reduce the input column to reduce the overall width,Maybe we don't use unitsonorder, unitsinstock, reorderlevel when adding new products, then remove them in gridview.

You need to make adjustments after deleting the unitsonorder, unitsinstock, and reorderlevel columns.There are 2 ways:

1. The addproduct method is still used, but it needs to pass in the values ​​of the unitsonorder, unitsinstock, and reorderlevel columns. We can do this in the inserting event handler,Use "hard-coded" or default values ​​for the above 3 columns.

2. Overload the addproduct method in the productsbll class,Make it unnecessary to pass in the values ​​of the unitsonorder, unitsinstock, and reorderlevel columns. Then, set the objectdatasource on the asp.net page to use the overloaded addproduct method.

Both of these methods work.In the previous tutorial we used the latter,Override the updateproduct method of the productsbll class multiple times.

to sum up:

Detailsview and formview controls have built-in inserting dataAnd gridview doesn't. However, we can use the footer row of the gridview control to achieve this.To display the footer line, just set the showfooter property to true. We can customize the footer row by converting each column into a templatefield and customizing the insertion interface in its footertemplate template.As we saw in this chapter,The footertemplate template can include controls such as buttons, textboxes, dropdownlists, checkboxes, data source controls, validation controls, etc.To facilitate user input,Add button, linkbutton or imagebutton are also required.

Click on When the add button is clicked, the insert () method of the objectdatasource control will be called, and the mapped data insert method will be used (specific to this article,Is the addproduct method of the productsbll class), before calling the specific insert data method,We need to pass the data typed in the insert interface to the insertparameters collection of the objectdatasource control. To achieve this,We should be in the inserting event handler of the objectdatasource control,Programmatically access the web control of the plug-in interface.

This tutorial explores techniques for optimizing the look of a gridview.The next series of tutorials,Let's see how to use binary data-such as images, pdfs, word documents, etc., and of course the data web control.

Happy programming!

About the Author

  • Previous Bootstrap4 a major update involving almost every line of code
  • Next Yii2 implementation method using ajax to return json