Insert a new record using the Gridview control in ASP. NET 2.0/3.5

Source: Internet
Author: User

I. Introduction
A batch of new powerful view controls, such as Gridview, FormView, and DetailsView, were introduced from ASP. NET 2.0. Through simple integration with data source controls, in many cases, you can develop powerful applications by simply configuring them. Unfortunately, the Gridview control does not support direct insert of new records as in the FormView and DetailsView controls. Figure 1 shows the typical use of controls to display database data.
Figure 1 use the GridView control to display the data in the Address Table of the VS2005 Sample Database
Anyone familiar with the Gridview control knows that everything in Figure 1 is the same, only one Insert operation is supported by default. I am currently using ASP. NET 3.5. The results are the same and still do not directly support the insert operation configuration.
Ii. Solutions
In fact, there are still some answers, which requires a better understanding of the Gridview control. We know that Gridview provides a lot of template support for developers to customize programming. Based on the general implementation interface of the insert operation, we can use the footer template function of the Gridview to provide a blank row for the user to enter the record in the last row of the Gridview control, in this way, the Gridview control supports the insert operation indirectly.

Iii. instance display
(1) create a sample Website and establish database Association
Start Visual Studio 2005/2008 and select the "ASP. NET Web Site" template to create a new example website GridViewExt. Drag a GridView control in Default. aspx on the Default page. Then, click the smart sensing prompt button in the upper-right corner of the GridView control. For this control, configure sqlcece1, a data source control of the SqlDataSource type. In addition, after simple wizard configuration, the data source control sqlperformance1 is created to associate with the demo database Depart. mdf, and is further associated with the DepartInfo table.
Tip: For simplicity, the demo database Depart. mdf contains only one table DepartInfo, and its architecture is very simple (the DepartID field is the primary keyword), as shown in Figure 2:

The final configuration parameters of the data source control sqlperformance1 (modified) are as follows:
<Asp: SqlDataSource ID = "SqlDataSource1" runat = "[url = javascript:;]Server[/Url]"
ConnectionString = "<% $ ConnectionStrings: DepartConnectionString %>"
SelectCommand = "SELECT DepartID, partition name FROM DepartInfo"
DeleteCommand = "Delete from DepartInfo where DepartID = @ DepartID"
InsertC
>
<DeleteParameters>
<Asp: Parameter Name = "DepartID" Type = "Int32"/>
</DeleteParameters>
<InsertParameters>
<Asp: Parameter Name = "DepartID" Type = "Int32"/>
<Asp: Parameter Name = "Parameter Name" Type = "String"/>
</InsertParameters>

</Asp: SqlDataSource>
(2) modify the page Default. aspx Layout
Our plan is to ask the user to select a record. When the user needs to add a record, click "add" and a blank row will be displayed in the last row of the Gridview, let the user input by field. When you decide not to enter a new blank record, you can press the "hide" button to return the blank row.
To achieve the above purpose, we can make full use of the footer template function of the Gridview for custom, because the table only has one Editable column named footer name; therefore, we only need to in the footer template of this column, the definition is as follows (note the bold part ):
<Asp: Button ID = "outAdd" runat = "Server" Text ="Add a new record "nclick =" outAdd_Click "/>
<Asp: GridView ID = "GridView1" runat = "server" AllowPaging = "True"
AllowSorting = "True" AutoGenerateColumns = "False" CellPadding = "4"ShowFooter = "false"
Performanceid = "sqlperformance1" ForeColor = "#333333" GridLines = "None"DataKeyNames = "DepartID">
<FooterStyle. BackColor = "# 5D7B9D" Font-Bold = "True" ForeColor = "White"/>
<RowStyle. backC0 "numbertype =" 1 "negative =" False "hasspace =" False "sourcevalue =" 7 "unitname =" F "w: st = "on"> 7F6F3 "ForeColor =" #333333 "/>
<Columns>
<Asp: TemplateField ShowHeader = "False">
<EditItemTemplate>
<Asp: LinkButton ID = "LinkButton1" runat = "server" CausesValidation = "True"
CommandName = "Update" Text = "Update"> </asp: LinkButton>
<Asp: LinkButton ID = "LinkButton2" runat = "server" CausesValidation = "False"
CommandName = "Cancel" Text = "Cancel"> </asp: LinkButton>
</EditItemTemplate>
<ItemTemplate>
<Asp: LinkButton ID = "LinkButton1" runat = "server" CausesValidation = "False"
CommandName = "Edit" Text = "Edit"> </asp: LinkButton>
</ItemTemplate>
<FooterTemplate>
<Asp: Button ID = "btnAdd" Runat = "server" Text = "Add" nClick = "btnAdd_Click"/>
<Asp: Button ID = "btnCancel" Runat = "server" Text = "Hide" nClick = "btnCancel_Click"/>
</FooterTemplate>
</Asp: TemplateField>
<Asp: TemplateField ShowHeader = "False">
<ItemTemplate>
<Asp: LinkButton ID = "LinkButton2" runat = "server" CausesValidation = "False"
CommandName = "Select" Text = "Select"> </asp: LinkButton>
</ItemTemplate>
<ItemTemplate>
<Asp: LinkButton ID = "LinkButton3" runat = "server" CausesValidation = "true"
CommandName = "Delete" Text = "Delete"> </asp: LinkButton>
</ItemTemplate>
</Asp: TemplateField>
<Asp: BoundField DataField = "DepartID" HeaderText = "DepartID"
InsertVisible = "False" ReadOnly = "True" SortExpression = "DepartID"/>
<Asp: TemplateField HeaderText = "comment name" SortExpression = "comment name">
<EditItemTemplate>
<Asp: TextBox ID = "DepartNameTextBox" runat = "server" Text = '<% # Bind ("container name") %>'> </asp: TextBox>
</EditItemTemplate>
<ItemTemplate>
<Asp: Label ID = "Label1" runat = "server" Text = '<% # Bind ("container name") %>'> </asp: Label>
</ItemTemplate>
<FooterTemplate>
<Asp: TextBox ID = "DepartNameBox" Runat = "server"> </asp: TextBox>
</FooterTemplate>
</Asp: TemplateField>
</Columns>
<PagerStyle. BackColor = "#284775" ForeColor = "White" HorizontalAlign = "Center"/>
<SelectedRowStyle. BackColor = "# E2DED6" Font-Bold = "True" ForeColor = "#333333"/>
<HeaderStyle. BackColor = "# 5D7B9D" Font-Bold = "True" ForeColor = "White"/>
<EditRowStyle. BackColor = "#999999" type = "regxph" text = "yourobjectname"/>
<AlternatingRowStyle. BackColor = "White" ForeColor = "#284775"/>
</Asp: GridView>
Note that an ASP. NET button "outAdd" is added before the Gridview control to check whether the control displays the <foottemplate> template content of the Gridview control. Obviously, this template is hidden at the start of page startup. Therefore, the Click Event code of this button (in the file Default. aspx. cx) is quite simple, as shown below:
Protected void outAdd_Click (object sender, EventArgs e)
{
GridView1.ShowFooter = true;

}
The following is the Code related to the Gridview. You can see that the DepartNameBox text box is provided in the <foottemplate> of the parameter name column for users to enter (because this field in this example is only a simple text field, for other types of fields, you need to create an ASP.. NET Control ).
In addition, note that the Add and Hide buttons are added in <FooterTemplate> In the first column. Their Event code is as follows:
<Script. runat = "server">
Void btnCancel_Click (object sender, EventArgs e)
{
GridView1.ShowFooter = false;
}

Void btnAdd_Click (object sender, EventArgs e)
{
TextBox t1 = GridView1.FooterRow. FindControl ("DepartNameBox") as TextBox;

SqlDataSource1.InsertParameters ["DepartName"]. DefaultValue = t1.Text;

SqlDataSource1.Insert ();

}
The Hide button event is used to cancel displaying the footer template of the Gridview. Therefore, the showfooter attribute is set to false, and the newly added record can be inserted (Added) by clicking the Add button) go to the database table.
The Add button is selected when the user decides to Add a record. The showfooter attribute is set to true to display the foottemplate of each column to display a new blank row.
Note thatHere, you must put the Click Event processor functions of the buttons "Add" and "Hide" in the ASPX file without putting them in the code file Default. aspx. cs; otherwise, the compilation error shown in 3 will occur.

Figure 3 "Add" and "Hide" Click Event processor functions are placed in the code file Default. aspx. cs, resulting in a compilation error prompt In addition, you must specify DataKeyNames = "DepartID" in the GridView1 attribute declaration. Otherwise, if you click "Delete" or "Update" at run time, a "classic" error message is displayed, 4.

Figure 4 error message caused by DataKeyNames of the GridView not specified 4. Observe the running results
Press F5 to run DEFAULT. ASPX on the Example page above. If everything goes well, you will observe the initial snapshot shown in Figure 5.

Figure 5 initial snapshot of the Sample Page Then, click "Add new record". The snapshot shown in Figure 6 is displayed.

Figure 6 example snapshot of running the "insert" function added to the GRIDVIEW Control
Obviously, after entering the Department name, click "Add" to Add the new department to the database table, and click "Hide" to Hide the footer.
V. Summary
The Gridview control introduced by ASP. NET 2.0 has powerful functions, but it also has some shortcomings. This article only shows one of them, and only shows a method for prompting the insert function for the Gridview control.
Finally, note that although the example in this article passes debugging in the right VS2008, according to my experience, there should be no problem in the ASP. NET 2.0 Environment of VS2005.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.