Click here to Skip to main content
15,891,748 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I use this Code for save TextBox Data into DataBase, but I have a Problem when I click save Button code run without any error and MessageBox Show "Recourd is saved",

but Data Not save in my DataBase,
I think Problem Not in My DataBase Connection Because My AutoNumber Code Work Fine

this is my Code
XML
<configuration>
    <configsections>
        <sectiongroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <section name="Project1.Properties.Settings">
        
    
    <connectionstrings>
        <add name="Project1.Properties.Settings.DataFileConnectionString" 
  connectionstring="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\DataFile.mdf;Integrated Security=True" providername="System.Data.SqlClient"/>
    
    <startup> 
        <supportedruntime version="v4.0" sku=".NETFramework,Version=v4.5">


What I have tried:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace Project1
{
    public partial class NewStudantEntry : Form
    {
        public NewStudantEntry()
        {
            InitializeComponent();
        }

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Project1.Properties.Settings.DataFileConnectionString"].ConnectionString);

        private void NewStudantEntry_Load(object sender, EventArgs e)
        {
            Autonumber();
        }

        // Auto Number in TextBox
        private void Autonumber()
        {
            string Query = "select MAX(StudantNumber) from StudantData";
            SqlCommand cd = new SqlCommand(Query, con);
            try
            {
                con.Open();
                var cont = cd.ExecuteScalar();
                var count = (cont == DBNull.Value ? 1 : Convert.ToInt32(cont) + 1);
                txtStudantNumber.Text = count.ToString("000");
                txtStudantNumber.Enabled = false;

            }

            finally
            {
                con.Close();
            }
        }

        private void SaveRecord()
        {
            string cmdstring = "Insert into StudantData (StudantNumber, ApplicationDate, StudantName, FatherName, Address, Address1, MobileNo, SecMobileNo, City, District, State, PinCode, Remark, UserID) VALUES (@StudantNumber, @ApplicationDate, @StudantName, @FatherName, @Address, @Address1, @MobileNo, @SecMobileNo, @City, @District, @State, @PinCode, @Remark, @UserID)";
            {
                using (SqlCommand cmd = new SqlCommand(cmdstring, con))
                {
                    con.Open();

                    cmd.Parameters.AddWithValue("@StudantNumber", txtStudantNumber.Text);
                    cmd.Parameters.AddWithValue("@ApplicationDate", dtpApplicationDate.Value.Date);
                    cmd.Parameters.AddWithValue("@StudantName", txtStudantName.Text);
                    cmd.Parameters.AddWithValue("@FatherName", txtFatherName.Text);
                    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
                    cmd.Parameters.AddWithValue("@Address1", txtAddress1.Text);
                    cmd.Parameters.AddWithValue("@MobileNo", txtMobileNo.Text);
                    cmd.Parameters.AddWithValue("@SecMobileNo", txtSecMobileNo.Text);
                    cmd.Parameters.AddWithValue("@City", txtCity.Text);
                    cmd.Parameters.AddWithValue("@District", txtDist.Text);
                    cmd.Parameters.AddWithValue("@State", txtState.Text);
                    cmd.Parameters.AddWithValue("@PinCode", txtPinCode.Text);
                    cmd.Parameters.AddWithValue("@Remark", txtRemark.Text);
                    cmd.Parameters.AddWithValue("@UserID", "Admin");

                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Recourd is saved", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    con.Close();
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveRecord();
        }
    }
}
Posted
Updated 7-Aug-20 22:56pm
v5

Do not do "autonumbering" like that: it's a recipe for some really nasty bugs. SQL Server is a multi-user database, so it's really quite possible that between you asking for the highest number and writing your data that any number of other user can have done the same. All it takes is one pair of users to end up with the same number, and the data in your DB can start to get seriously compromised.

Instead, use an IDENTITY field in SQL Server (or a UNIQUEIDENTIFIER) and let SQL Server sort out the uniqueness - it will get it right! It's also a lot more efficient than two round trips to SQL ...

As far as the problem you have noticed, as Garth says the debugger is the place to start. But assuming you do get a "Recourd is saved" (sic) message box, then you need to look at how you are determining that the row is not being stored: what makes you so sure it isn't? Since you get the MessageBox, you aren't getting an exception in that code - which implies that you aren't looking at the right place when you check!
 
Share this answer
 
Comments
Amar chand123 8-Aug-20 7:08am    
When i change "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\DataFile.mdf;Integrated Security=True"
to
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\HP\source\repos\Project1\Project1\Data\DataFile.mdf;Integrated Security=True"

my Code Woke Fine and Data Save and show in my DataBase Correctly
but I Don't Know, Why?
OriginalGriff 8-Aug-20 9:02am    
Why do you think?
Do you think it is at all likely that SQL Server will look for databases in your project folder? Or do you think it keeps a separate folder for it's databases, referred to as "|DataDirectory|"?

And two other details:
1) Never hardcode connection strings - always use a configuration file, or you will have to change the string in multiple places for each and every installation and that's a PITA.
2) Don't Attach databases - that's a special debugging feature that is only applicable to Express editions of Sql Server and it will fail massively if you try to use it in release code (as well as generating multiple copies of a multiuser database). Give the DB to SQL Server and let it look after it in its DataDirectory instead.
You make the classic mistake of not using the code correctly. As you can see from SqlCommand.ExecuteNonQuery Method (System.Data.SqlClient) | Microsoft Docs[^], there is a return value to tell you whether it worked or not. But you have ignored that and just assumed that it worked. Never post "success" messages unless you first check the result of the method call.
 
Share this answer
 
Comments
Amar chand123 8-Aug-20 7:07am    
When i change "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\DataFile.mdf;Integrated Security=True"
to
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\HP\source\repos\Project1\Project1\Data\DataFile.mdf;Integrated Security=True"

my Code Woke Fine and Data Save and show in my DataBase Correctly
but I Don't Know, Why?
Richard MacCutchan 8-Aug-20 8:17am    
There is no way that we can find out. You need to use the debugger to step through the code and find out what is happening.
I think you should use your debugger and make absolutely sure your code in SaveRecord() is being run.

Set a breakpoint on this line
string cmdstring = "Insert into StudantData (StudantNumber, ApplicationDate, StudantName, FatherName, Address, Address1, MobileNo, SecMobileNo, City, District, State, PinCode, Remark, UserID) VALUES (@StudantNumber, @ApplicationDate, @StudantName, @FatherName, @Address, @Address1, @MobileNo, @SecMobileNo, @City, @District, @State, @PinCode, @Remark, @UserID)";
then single step and see what happens

btw, not using a try...catch...finally in SaveRecord ? Dangerous
 
Share this answer
 
<add name="Project1.Properties.Settings.DataFileConnectionString" 

="" connectionstring="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\DataFile.mdf;Integrated Security=True" providername="System.Data.SqlClient">


There's an extra ="" in your app.config file. Remove that as it may be screwing with the XML parser for the config file.

Also, the closing tag for the add tag is missing. Add a forward slash to the end of the line, just before the >.

<add name="Project1.Properties.Settings.DataFileConnectionString" 
    connectionstring="Data Source=LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\DataFile.mdf;Integrated Security=True"
    providername="System.Data.SqlClient" />
 
Share this answer
 
Comments
Amar chand123 8-Aug-20 3:04am    
Problem still same
Dave Kreskowiak 8-Aug-20 18:19pm    
I didn't say it was a fix. I'm just pointing out the things that are obviously wrong.
Dave Kreskowiak 8-Aug-20 18:27pm    
First thing is every time you run the app under the debugger in Visual Studio, your database file is being overwritten by the copy you have in the project. The data you save is saved to the copy in the DataDirectory. The next time you run the app on the debugger, that copy is overwritten, destroying the data you saved on the previous run.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900