Learn ASP.NET MVC How to's for free here.
Your details are safeBuyer's Satisfaction Contact Us
 Welcome Guest | Register | Login Why online training? | Buyers FAQs | Testimonials | Contact us 


Subscribe to Tutorials feed

Our Quality Professors

Our professors includes
Contact us for training ...

Technology Tags

ADO.NET AdRotator ASP.NET ASP.NET-AJAX Authentication-and-Authorization---LoginView BulletedList Button Caching Calendar Chart CheckBoxList Cookies CSharp CSS Cusotm-Control Debugging-and-Tracing DetailsView DropDownList-and-ListBox DropDownList-and--ListBox Error-handling FileUpload Forms-Authentication GridView HiddenField HTML HyperLink Image ImageButton ImageMap Javascript jQuery jQuery-Ajax jQuery-Attributes jQuery-effects jQuery-Effects jQuery-Events jQuery-How-to-Solution jQuery-Manipulations jQuery-Selectors jQuery-Traversing Label-and-Literal LinkButton ListView Localization-and-Globalization Login LoginName LoginStatus LoginStatus-and-LoginName-and-other-controls LoginView MasterPage Menu Meta-tags Panel PlaceHolder RadioButtonList Repeater Security Session-Management TextBox Themes-and-Skins Url-Routing User-Control Validations visual-studio Webconfig Working-with-Files-and-Folders

Search Tutorials

eg. asp.net


More ...


How to insert records into the database?

by: Itfunda Product Type: Tips and Tricks (Books) Technologies: ASP.NET  ADO.NET 

To connect to the database and insert records into the database, we can follow this approach.

        <asp:Label ID="lblMessage" runat="server" ForeColor="Green" />
            Create, Read, Update, Delete operation</h5>
                        First name:
                        <asp:TextBox ID="txtFirstName" runat="server" />
                        Last name:
                        <asp:TextBox ID="txtLastName" runat="server" />
                        <asp:TextBox ID="txtAge" runat="server" />
                        <asp:DropDownList ID="dropActive" runat="server">
                            <asp:ListItem Text="Yes" Value="True" />
                            <asp:ListItem Text="No" Value="False" />
                        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SubmitData" />
Code Behind
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
/// <summary>
/// Submits the data.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void SubmitData(object sender, EventArgs e)
    int returnValue = 0;
    // get the connection
    using (SqlConnection conn = new SqlConnection(_connStr))
        // write the sql statement to execute
        string sql = "INSERT INTO PersonalDetail (FirstName, LastName, Age, Active) VALUES " + "(@FirstName, @LastName, @Age, @Active)";
        // instantiate the command object to fire
        using (SqlCommand cmd = new SqlCommand(sql, conn))
            // attach the parameter to pass, if no parameter is in the sql no need to attach
            SqlParameter[] prms = new SqlParameter[4];
            prms[0] = new SqlParameter("@FirstName", SqlDbType.VarChar, 50);
            prms[0].Value = txtFirstName.Text.Trim();
            prms[1] = new SqlParameter("@LastName", SqlDbType.VarChar, 50);
            prms[1].Value = txtLastName.Text.Trim();
            prms[2] = new SqlParameter("@Age", SqlDbType.Int);
            prms[2].Value = int.Parse(txtAge.Text.Trim());
            prms[3] = new SqlParameter("@Active", SqlDbType.Bit);
            prms[3].Value = bool.Parse(dropActive.SelectedValue);
            returnValue = cmd.ExecuteNonQuery();
    if (!returnValue.Equals(0))
        lblMessage.Text = " Records inserted successfully !";
In the above code snippet, on the aspx page we have three TextBoxes, a DropDownList (First name, Last name, Age & Active) and a Submit button. On click of the Submit, we have fired the SubmitData server side method.

In the SubmitData method, we have a SqlConnection object and SqlCommand object in the same way we had for fetching the records from the database. The only change here is the sql command that is going to execute. As our sql command has four parameters, we need to attach four SqlParameters to the command object. To execute the Insert, Update and Delete sql query, we need to fire the ExecuteNonQuery method of the command object (before executing this command, ensure that the database connection is open and after executing close this immediately to avoid any memory leak).

ExecuteNonQuery method returns number of records affected with the Sql statement. So we have checked if it is not equal to 0 then wrote success message.


This post is the part of following product

.NET How to Tips and Tricks (700+)

.NET How to Tips and Tricks (700+) This ".NET How to Tips and Tricks" contains solutions of hundreds of technical problems related with ASP.NET, ASP.NET MVC, SQL Serer, jQuery etc. that help you to develop real time .NET projects easily. It has following features
  • Video tutorials
  • Demo projects source code
  • eBook with to-the point explanations & output
prepared by Sheo Narayan (Ex Microsoft MVP).

 Latest tutorials

 Posts from Itfunda

Share this to:

Facebook Twitter LinkedIn Google+ Pinterest Email Addthis

About Us | Contact Us | Partners | Privacy Policy | Terms and Conditions | Buyer's FAQs | Seller's FAQs | Currency Converter | Go Top

Notice: If you found someone plagiarising our content/materials, kinldy let us know.

© SN ITFunda Services LLP. Site design and layout is copyright to SN ITFunda Services LLP.
Copying or duplicating or mimicking the site design and layout is prohibited and will be treated as a legal offence and will be prosecuted.
Logos, company, product, service or other names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 16102020 | 5/25/2024 5:16:08 AM