I am trying to insert data into a sql server database table using sqlDataAdapter and adding newrow method.But the values entered are not saved in the database.What I did is............

string sql = "Select * from Users";               
                dataCmd.CommandText = sql;

                SqlDataAdapter da = new SqlDataAdapter(dataCmd);
                da.SelectCommand = new SqlCommand(sql, cn);


                DataTable UserTable = new DataTable();

                DataRow dtr;
                dtr = UserTable.NewRow(); 

                dtr["UserID"] = txtID.Text;                
                dtr["User_Name"] = txtName.Text;              

                MessageBox.Show("Row Inserted");

What has gone wrong here?????

Or can you help me to solve this???

Thanks a lot..

Recommended Answers

All 2 Replies

You need to specify a Select, Insert, Delete, and Update query for your data adapter. You also need to call .Update() on your data adapter after you add, edit, or delete a DataRow in your DataSet/DataTable.

If you modify a row then re-fill your dataset you're blowing away the changes.


You forgot to update the SqlDataAdapter -> an example from MSDN

public DataSet CreateCmdsAndUpdate(string connectionString,
    string queryString) 
    using (OleDbConnection connection = new OleDbConnection(connectionString))
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        adapter.SelectCommand = new OleDbCommand(queryString, connection);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);


        DataSet customers = new DataSet();

        //code to modify data in dataset here


        return customers;

In your case you must do this:

SqlCommandBuilder builder = new SqlCommandBuilder(da);

hope this helps!


commented: Code tags and solving threads on your second post! Good work :) +5
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.