Aliza
Aliza

Reputation: 1

Adding Records in Database in C# 2005

NET C# 2005, i m creating a database in c# in which all records are saving and updating and deleting at the run time but whenever i closes that application, my all records were lost, i wanted them to be stored in the SQL database so whenever i open my application i have all my saved records, the code which i m trying is as follows.

namespace WindowsApplication13
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void table1BindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        this.Validate();
        this.table1BindingSource.EndEdit();
        this.table1TableAdapter.Update(this.database2DataSet.Table1);

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'database2DataSet.Table1' table. You can move, or remove it, as needed.
        this.table1TableAdapter.Fill(this.database2DataSet.Table1);

    }
}

}

Upvotes: 0

Views: 178

Answers (4)

Arjan Einbu
Arjan Einbu

Reputation: 13682

Your code looks about right (haven't tested it), so maybe the problem is that you're testing this with a runtime attached database. You are if your connectionstring has an "AttachDbFilename" property instead of "Database" or "Initial Catalog", like this one:

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CateringDB.mdf;Integrated Security=True;User Instance=True"

What happens then is that each time you compile your program from Visual Studio, your database file is copied to the output directory (/bin/debug or /bin/release), and any modifications are done on the copy of the database, not the one you see in the Solution Explorer.

This problem won't appear after deployment, when you're no longer running the program from Visual Studio.

You can change this behaviour by either:

  • Selecting the .mdf file in Solution Explorer, and then in properties (press F4) change the setting of "Copy to output directory" to something else than "Copy Always". (My recomended solution.)
  • Changing the connectionstring to point to an absolute or relative path, like "AttachDbFileName=c:\catering.mdb" or "AttachDbFileName=....\Catering.mdb" (thus removing the "|DataDirectory|" part.

Upvotes: 2

Renatas M.
Renatas M.

Reputation: 11820

I think your table1TableAdapters UpdateCommand property is empty.

Upvotes: 0

Akram Shahda
Akram Shahda

Reputation: 14781

You need to use DbDataAdapter.Update Method

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

I think what you want is a basic understanding about how to save data in to a SQL database and retrieve from it using C#. Google would be your best friend in this case. You can follow this link as a starting point. It describes how you can save and load data to and from a database using C#

Upvotes: 1

Related Questions