Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
im trying to data insert into database, this is my code every thing is fine no error The problem is that just insertion data not save in my DataBase1.mdf i dont know why?
When my program is running, the first time that I insert data, they show in gridView1 but not store in database1.mdf
anyone help me
DB name : inventry
table name: addProduct
column : pid,title,descrtion,type,vendor,price,isbn


app.config file

XML
<connectionStrings>
        <add name="inven" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\inventry.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>



Button code file

C#
private void button1_Click(object sender, EventArgs e)
        {
            String con = ConfigurationManager.ConnectionStrings["inven"].ConnectionString;

            SqlConnection connection = new SqlConnection(con);

            connection.Open();
  SqlCommand cmd = new SqlCommand("Insert into addProduct(title,descrtion,type,vendor,price,isbn) values(@title,@descrtion,@type,@vendor,@price,@isbn)", connection);

            cmd.Parameters.AddWithValue("@title", textBox1.Text);
            cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
            cmd.Parameters.AddWithValue("@type", textBox3.Text);
            cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
            cmd.Parameters.AddWithValue("@price", textBox5.Text);
            cmd.Parameters.AddWithValue("@isbn", textBox6.Text);

            int rows = cmd.ExecuteNonQuery();
            if (rows != 0)
            {
                MessageBox.Show("Inserted");
            }
            else
            {
                MessageBox.Show("Insertion failure");
            }
           connection.Close();
}
Posted
Updated 31-Oct-14 7:50am
v3
Comments
Rajesh waran 31-Oct-14 8:31am    
Can you provide your table design?
Or Try to debug your code, check the rows value here ( int rows = cmd.ExecuteNonQuery(); )
You should get 1 in rows,bcoz here you are going to affect only one row. then change the condition like if (rows > 0)
raajaakhan 31-Oct-14 13:53pm    
i updated my question now see
Shemeemsha (ഷെമീംഷ) 31-Oct-14 8:52am    
What is the error you are getting.?
Debug your code and add the error details in your question .
raajaakhan 31-Oct-14 13:36pm    
no error problem is my data is not store/save in database1.mdf
ZurdoDev 31-Oct-14 8:56am    
It looks right so either you are getting an error it is working and perhaps you're looking in the wrong place.

Check you Load event: When the user clicks a button, the load event is fired before the Click event, so if you specifically clear (or set any values into) the textboxes in you Load event handler, those will be that values it inserts to the database.

To fix that, check the IsPostBack[^] property, and only do such initialisations when it is false.
 
Share this answer
 
C#
protected void Page_Load(object sender, EventArgs e)
{
    // Please check the OG's Answer why this is important
    if (!IsPostBack)
    {
        // load data in page load only in first time
        LoadData();
    }
}

private void LoadData()
{
    //Load data from database and bind it to gridview
}

protected void Button1_Click(object sender, EventArgs e)
{
    String constring = ConfigurationManager.ConnectionStrings["inven"].ConnectionString;
    //use [] for the column names if those are reserved sql keywords like description, type etc..
    string insertSql = "insert into addProduct([title],[descrtion],[type],[vendor],[price],[isbn]) values(@title,@descrtion,@type,@vendor,@price,@isbn)";

    using (SqlConnection connection = new SqlConnection(constring))
    using (SqlCommand cmd = new SqlCommand(insertSql, connection))
    {
        cmd.Parameters.AddWithValue("@title", textBox1.Text);
        cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
        cmd.Parameters.AddWithValue("@type", textBox3.Text);
        cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
        cmd.Parameters.AddWithValue("@price", textBox5.Text);
        cmd.Parameters.AddWithValue("@isbn", textBox6.Text);
        connection.Open();
        int rows = cmd.ExecuteNonQuery();
        string message = "Insertion failure";
        if (rows > 0)
        {
            message = "Inserted";
        }
        //MessageBox.Show will not work in ASP.NET, use below
        ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('" + message + "');", true);
        //load newly added data to gridview
        LoadData();
    }
}


UPDATE
======

right click on your database file in solution explorer and select build action as copy if never. I think your data lost when you run next time because of the visual study replace old database with new one.
 
Share this answer
 
v3
Comments
raajaakhan 3-Nov-14 9:18am    
im still looking answer my question
DamithSL 3-Nov-14 9:27am    
have you tried my solution?
raajaakhan 3-Nov-14 12:20pm    
my code for windows desktop application and your i think asp.net
DamithSL 3-Nov-14 12:31pm    
Yes, this code sample will not useful if you have windows form app.
raajaakhan 3-Nov-14 12:22pm    
can i try this on windows form application?
Hi,

Your code is correct and working fine....

The problem is when you are in Debug Mode or Release mode...

Database file created automatically when the program is running.. and the data you have inserted is stored in that folder..inside BIN

Please check the Debug folder inside Bin folder, you will fin the Access database file with your inserted data...

Below the working code...for windows/ desktop application

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

namespace WFDS
{
    public partial class AccessDB : Form
    {
         OleDbConnection conn = new OleDbConnection();
         String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Data\\BookStore.accdb;Persist Security Info=True";
        public AccessDB()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
              
                conn.Open();




                OleDbCommand cmd = new OleDbCommand("Insert into product(title,descrtion,type,vendor,price,isbn) values(@title,@descrtion,@type,@vendor,@price,@isbn)", conn);

                cmd.Parameters.AddWithValue("@title", textBox1.Text);
                cmd.Parameters.AddWithValue("@descrtion", textBox2.Text);
                cmd.Parameters.AddWithValue("@type", textBox3.Text);
                cmd.Parameters.AddWithValue("@vendor", textBox4.Text);
                cmd.Parameters.AddWithValue("@price", textBox5.Text);
                cmd.Parameters.AddWithValue("@isbn", textBox6.Text);

                int rows = cmd.ExecuteNonQuery();
                if (rows != 0)
                {
                    MessageBox.Show("Inserted");
                }
                else
                {
                    MessageBox.Show("Insertion failure");
                }
                conn.Close();



            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
 
   
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string sql = "SELECT *  FROM product";
            DataSet ds = new DataSet();
           
          
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
            adapter.Fill(ds);
            int dd = ds.Tables[0].Rows.Count;
            dataGridView1.DataSource = ds.Tables[0];
            conn.Close();
           
        }

        private void AccessDB_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = connection;
        }
    }
}




The database file is stored in the Bin\Debug or BIN\Release directory

Thanks,

Ullas Krishnann
 
Share this answer
 

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