Welcome to Dream.In.Code
Become a C# Expert!

Join 136,937 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,849 people online right now. Registration is fast and FREE... Join Now!




DataGridView Fill() and Update() reacting strangely

 
Reply to this topicStart new topic

DataGridView Fill() and Update() reacting strangely

Footsie
20 Mar, 2008 - 05:17 AM
Post #1

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
I have a DataGridview which I want to fill from my dataset when I click "View" on a ToolStripMenu.
I have an "Update" button on the ToolStrip to update current rows and insert new rows, and I have a "Clear" button to clear the datagrid.

When I click "View" the grid loads fine. I then edit a row and click "Update". When I click "Clear" the grid clears. When I click "View" again the grid loads - minus my edit (the edit is not getting updated to the DB)
  1. It updates the edit only if I first click in another row then click "Update",
  2. ALL the rows are then altered to my edit and overwritten (not good at all!!)
csharp

//I'm not sure whether my "Clear" event here is correct - it clears
//the dataset.table not just the dataGridView (not sure how to do it differently)

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
this.dsTracking.tracking.Clear();
}

private void viewToolStripMenuItem_Click(object sender, EventArgs e)
{
this.adapter.Fill(this.dsTracking.tracking);
}

private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
this.adapter.Update(this.dsTracking.tracking);
}


Surely the Update and Fill methods shouldn't be reacting like this?
Any help would be great!
Thanks.

This post has been edited by Footsie: 20 Mar, 2008 - 05:19 AM
User is online!Profile CardPM
+Quote Post

PsychoCoder
RE: DataGridView Fill() And Update() Reacting Strangely
20 Mar, 2008 - 05:21 AM
Post #2

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 8,998



Thanked: 126 times
Dream Kudos: 8625
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
We need to see your Select & Update queries
User is offlineProfile CardPM
+Quote Post

Footsie
RE: DataGridView Fill() And Update() Reacting Strangely
20 Mar, 2008 - 05:29 AM
Post #3

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
Right, here we go:

SELECT:
sql
SELECT     Customer, Name, Qty, GoodsDescrip, Supplier, Couriers, OrderPlaced, Printer, ETA_Printer, ETA_Customer, Invoiced
FROM tracking;


UPDATE:
sql

UPDATE tracking
SET Customer = ?parCustomer, Name = ?parName, Qty = ?parQty, GoodsDescrip = ?parGoodsDescrip, Supplier = ?parSupplier, Couriers = ?parCourier,
Printer = ?parPrinter, ETA_Printer = ?parETA_Printer, ETA_Customer = ?parETA_Customer, Invoiced = ?parInvoiced;


The project is basically a digital Whiteboard to keep track of Orders.
DB is MySql.
User is online!Profile CardPM
+Quote Post

PsychoCoder
RE: DataGridView Fill() And Update() Reacting Strangely
20 Mar, 2008 - 05:44 AM
Post #4

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 8,998



Thanked: 126 times
Dream Kudos: 8625
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
This block of code will indeed remove all the items from your DataSet. If you just want to clear the DataGridView try this


csharp

private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
YourDataGridView.DataSource() = null
}


That will simply remove all the rows from your DataGridView. As far as updating, your DataSet is filled with DataTables (in this case it looks like just one), so try updating the DataTable not the DataSet


csharp

private void updateToolStripMenuItem_Click(object sender, EventArgs e)
{
this.adapter.Update(this.dsTracking);
}



Im just taking stabs at this, Ive never worked with the grids using the drag & drop controls, Ive always did the binding and such at runtime not design time.


EDIT: I made a modification to the code I posted, I just throw the DataSet into the Update command. By the way what database are you using?

This post has been edited by PsychoCoder: 20 Mar, 2008 - 05:49 AM
User is offlineProfile CardPM
+Quote Post

Footsie
RE: DataGridView Fill() And Update() Reacting Strangely
20 Mar, 2008 - 05:51 AM
Post #5

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
Cool!
I'll give this a bash.
Thanks Psycho!

EDIT: Database = MySql

This post has been edited by Footsie: 20 Mar, 2008 - 05:54 AM
User is online!Profile CardPM
+Quote Post

Footsie
RE: DataGridView Fill() And Update() Reacting Strangely
20 Mar, 2008 - 06:26 AM
Post #6

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
No, setting the DataSource to null clears the gridView, but when I click on "View" again the DataSource is still null and so the gridView does not display anything. I think my original this.dsTracking.tracking.Clear(); is better for my uses here. (unless someone knows better smile.gif)

As to the this.adapter.Update(this.dsTracking); it reacts with the exact same problem, ie:
  • It updates the gridView only if I first click in another row then click "Update",
  • Every row's value is then changed to my updated value, instead of just the one edited row

Here is an example of the ouptut in my gridView in order to try and explain better:

CODE

Customer:
----------------
George
Jane
Joe     <---I edit this to "Allan" and then click Update


Then all of them change to Allan for some reason:

CODE

Customer:
-------------
Allan
Allan
Allan


Any other ideas?
User is online!Profile CardPM
+Quote Post

Footsie
RE: DataGridView Fill() And Update() Reacting Strangely
8 Apr, 2008 - 08:33 AM
Post #7

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
I've finally come back to this project (after been busy on a few others). I've tried creating this from scratch again but I hit the same weird Update behaviour. Anyone know why this is happening?
User is online!Profile CardPM
+Quote Post

Jayman
RE: DataGridView Fill() And Update() Reacting Strangely
8 Apr, 2008 - 08:44 AM
Post #8

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 6,959



Thanked: 43 times
Dream Kudos: 500
Expert In: C#, VB.NET, Java

My Contributions
The reason why all your rows are updating in the database is because your Update statement doesn't include a WHERE statement. So instead of specifically telling the DB which row to update, you are saying update all rows.

You need to include a where statement that references the old value of the row you want to change.

Something along the following lines, where "?Customer" is the value of the row to change:
SQL
UPDATE tracking
SET Customer = ?parCustomer, Name = ?parName, Qty = ?parQty, GoodsDescrip = ?parGoodsDescrip, Supplier = ?parSupplier, Couriers = ?parCourier,
Printer = ?parPrinter, ETA_Printer = ?parETA_Printer, ETA_Customer = ?parETA_Customer, Invoiced = ?parInvoiced
WHERE Customer = ?Customer;


As for why you have to leave the row before it will update, I believe that is expected behavior. Same thing happens in SQL Server, you have to leave the row you are editing before it will update the DB with the changes. You just need to tab out of the row before hitting the update button.
User is offlineProfile CardPM
+Quote Post

Footsie
RE: DataGridView Fill() And Update() Reacting Strangely
8 Apr, 2008 - 09:56 AM
Post #9

D.I.C Regular
Group Icon

Joined: 20 Sep, 2007
Posts: 305



Thanked: 4 times
Dream Kudos: 50
My Contributions
Excellent!
That sorted out the issue. I added an auto incrementing primary key column and put the WHERE statement on that:
WHERE EntryID = ?EntryID

Thank you for checking through my code,
Jayman.

User is online!Profile CardPM
+Quote Post

quentinuys
RE: DataGridView Fill() And Update() Reacting Strangely
22 Apr, 2008 - 07:31 AM
Post #10

New D.I.C Head
*

Joined: 22 Apr, 2008
Posts: 3

I have the same problem.

I have a Form with a datagridview on it. With that i have a update and reload button. Everything works fine, Butt!!
when i go to my server explorer and view the database, it go backs to normal. When I run the program after that, the datagridview is back to normal aswell..

Please help me out...

Here is my Code..
CODE

public partial class Form3 : Form
    {
        
        private BindingSource bindingSource1 = new BindingSource();
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        DataSet ds = new DataSet();

        public Form3()
        {

            InitializeComponent();
            dataGridView1.Dock = DockStyle.Fill;

            
            FlowLayoutPanel panel = new FlowLayoutPanel();
            panel.Dock = DockStyle.Top;
            panel.AutoSize = true;
            panel.Controls.AddRange(new Control[] { button1, button2 });

            this.Controls.AddRange(new Control[] { dataGridView1, panel });
            this.Text = "DataGridView databinding and updating demo";
        }

        private void invoiceToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        private void Form3_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = bindingSource1;
           // Utilities myUtilities = new Utilities();
           // myUtilities.GetData("select * from Client");
           GetData("select * from Client");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetData(dataAdapter.SelectCommand.CommandText);
           // Utilities myUtilities = new Utilities();
           // myUtilities.GetData(dataAdapter.SelectCommand.CommandText);
        }

        private void button2_Click(object sender, EventArgs e)
        {
          
            //dataAdapter.Update(ds,"Client");
            this.dataAdapter.Update(this.ds, "Client");

            
        }

        private void GetData(string selectCommand)
        {
            try
            {
                // Specify a connection string. Replace the given value with a
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\FS.mdf;Integrated Security=True;User Instance=True";


                // Create a new data adapter based on the specified query.
                dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
                dataAdapter.Fill(ds, "Client");
                // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
                
                dataAdapter.Fill(ds);
                // Populate a new data table and bind it to the BindingSource.
                DataTable table = new DataTable();
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;

                // Resize the DataGridView columns to fit the newly loaded content.
                dataGridView1.AutoResizeColumns(
                    DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
            }
            catch (SqlException)
            {
                MessageBox.Show("To run this example, replace the value of the " +
                    "connectionString variable with a connection string that is " +
                    "valid for your system.");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            GetData(textBox1.Text);
        }

      
    }



Any help will be apriciated. blink.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/3/08 10:47PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month