Link to home
Start Free TrialLog in
Avatar of Moti Mashiah
Moti MashiahFlag for Canada

asked on

windows form

Hi guys ,

I'm trying to update datagrideview with button, here is my code:

//update button
        private void button1_Click(object sender, EventArgs e)
        {

            //PasssaveEntities db = new PasssaveEntities();

            //var upd = (from u in db.t_Login where u.Id == u.Id select u);

            //dataGridView1.DataSource = (upd);
    
        }

Open in new window

Avatar of Vel Eous
Vel Eous

Your code inside the button1_Click event handler is commented out.

That aside, try using a BindingList<T> when binding a datasource as it supports change notifications:

var bindinglist = new BindingList<T>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

Open in new window

Avatar of Moti Mashiah

ASKER

Thanks for the quick answer but I didn't really understand your example.

can you please be more specific..I'm really new to this world.


thanks ,
Actually I would like to update the datagridview1 please see example what i did now.
it still look not right.

PasssaveEntities db = new PasssaveEntities();

            var upd = (from u in db.t_Login where u.Id == u.Id select u);

            var bindinglist = new BindingList<T>(list);
            var source = new BindingSource(upd, null);
            dataGridView1.DataSource = source;

Open in new window


Please can you direct me how to write update code to the datagridview with LINQ.


thanks ,
BindingList<T> is a generic, your substitute T with either an interface or a concrete type, for example:

var myBindingList = new BindingList<string>(new List<string> { "Hello", "World" });

Open in new window


The above will create a new BindingList of type string.

I don't know what type your LINQ query is returning (i.e. var upd is of what concrete type?), however, you are looking for something like the following:

private void button1_Click(object sender, EventArgs e)
{
    PasssaveEntities db = new PasssaveEntities();
    var upd = (from u in db.t_Login where u.Id == u.Id select u).ToList();
    var bindingList = new BindingList<T>(upd); // replace T with the type of upd
    var dataSource = new BindingSource(bindingList, null);
    dataGridView1.DataSource = dataSource;
}

Open in new window

k , i did this one and still dont know what do you mean regarding the T type

 private void button1_Click(object sender, EventArgs e)
        {
            

            PasssaveEntities db = new PasssaveEntities(); //connection to my database
            var upd = (from u in db.t_Login where u.Id == u.Id select u).ToList(); //query from t_login table
            var bindingList = new BindingList<>(upd); //
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;
    
        }

Open in new window

the udp is the linq variable.
Now I was trying this:

private void button1_Click(object sender, EventArgs e)
        {
            

            PasssaveEntities db = new PasssaveEntities();
            var upd = (from u in db.t_Login where u.Id == u.Id select u).ToList();
            var bindingList = new BindingList<t_Login>(upd); // replace T with the type of upd
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;
    
        }

Open in new window

You're almost there with your last attempt.

The T in <T> is a placeholder for any type of object you care to substitute it with.  Your LINQ query is returning either an IQueryable<T> or IEnumerable<T>.  The T in the return value of the LINQ query is what we're interested in as this is what you should put as the T in BindingList<T>.

If you put a breakpoint on var bindingList and run the debugger, when it stops, inspect var upd for the type.
I did this :

            PasssaveEntities db = new PasssaveEntities();
            var upd = (from u in db.t_Login where u.Id == u.Id select u).ToList();
            var bindingList = new BindingList<IEnumerable>(upd); // replace T with the type of upd
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;

and I'm getting error in IEnumerable
Nope.  Read my previous comment carefully.

var upd = (from u in db.t_Login where u.Id == u.Id select u);

Open in new window


var is an implicitly typed local variable, its actual type is determined at compile time.  If you were to type the above code explicitly it would be either:

IEnumerable<T> upd = (from u in db.t_Login where u.Id == u.Id select u);

Open in new window

or
IQueryable<T> upd = (from u in db.t_Login where u.Id == u.Id select u);

Open in new window


What is T in this case, is it a string object, a User object, is it a database table such as tblLogins which comes from your database ORM like Entity Framework?

Use the debugger to find out if you're not sure.
Avatar of it_saige
At it's simplest, this is what Tchuki is referring to:

A quick simple project:

Form1.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EE_Q28553270
{
	public partial class Form1 : Form
	{
		private BindingList<DataItem> dataItems = new BindingList<DataItem>();

		public Form1()
		{
			InitializeComponent();
			dataGridView1.DataSource = dataItems;
		}

		private void OnClick(object sender, EventArgs e)
		{
			if (sender is Button)
			{
				Button btn = sender as Button;
				if (btn == btnAdd)
				{
					using (Form2 frm2 = new Form2(dataItems.Count > 0 ? (dataItems.Max(x => x.ID) + 1) : 1))
					{
						if (frm2.ShowDialog() == DialogResult.OK)
						{
							dataItems.Add(frm2.NewItem);
							MessageBox.Show("New item should be added.");
						}
						else
							MessageBox.Show("Cancelled adding new item.");
					}
				}

				if (btn == btnRemove)
				{
					foreach (DataGridViewRow item in dataGridView1.SelectedRows)
						dataItems.Remove(item.DataBoundItem as DataItem);
				}
			}
		}

		private void OnLoad(object sender, EventArgs e)
		{
			dataItems.Add(new DataItem() { ID = 1, Name = "John Doe", Comment = "A simple man" });
			dataItems.Add(new DataItem() { ID = 2, Name = "Jane Doe", Comment = "A simple woman"});
			dataItems.Add(new DataItem() { ID = 3, Name = "Harry Henderson", Comment = "A gentle beast" });
		}
	}
}

Open in new window


Form1.Designer.cs -
namespace EE_Q28553270
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.dataGridView1 = new System.Windows.Forms.DataGridView();
			this.btnAdd = new System.Windows.Forms.Button();
			this.btnRemove = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGridView1
			// 
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Location = new System.Drawing.Point(12, 12);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
			this.dataGridView1.Size = new System.Drawing.Size(463, 205);
			this.dataGridView1.TabIndex = 0;
			// 
			// btnAdd
			// 
			this.btnAdd.Location = new System.Drawing.Point(298, 229);
			this.btnAdd.Name = "btnAdd";
			this.btnAdd.Size = new System.Drawing.Size(85, 23);
			this.btnAdd.TabIndex = 1;
			this.btnAdd.Text = "Add Item";
			this.btnAdd.UseVisualStyleBackColor = true;
			this.btnAdd.Click += new System.EventHandler(this.OnClick);
			// 
			// btnRemove
			// 
			this.btnRemove.Location = new System.Drawing.Point(389, 229);
			this.btnRemove.Name = "btnRemove";
			this.btnRemove.Size = new System.Drawing.Size(85, 23);
			this.btnRemove.TabIndex = 2;
			this.btnRemove.Text = "Remove Item";
			this.btnRemove.UseVisualStyleBackColor = true;
			this.btnRemove.Click += new System.EventHandler(this.OnClick);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(487, 264);
			this.Controls.Add(this.btnRemove);
			this.Controls.Add(this.btnAdd);
			this.Controls.Add(this.dataGridView1);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dataGridView1;
		private System.Windows.Forms.Button btnAdd;
		private System.Windows.Forms.Button btnRemove;
	}
}

Open in new window


Form2.cs -
using System;
using System.Windows.Forms;

namespace EE_Q28553270
{
	public partial class Form2 : Form
	{
		public DataItem NewItem { get; set; }

		public Form2(int ID)
		{
			InitializeComponent();
			tbID.Text = ID.ToString();
			NewItem = new DataItem() { ID = ID };
		}

		private void OnClick(object sender, EventArgs e)
		{
			if (sender is Button)
			{
				Button btn = sender as Button;
				if (btn == btnOK)
				{
					NewItem.Name = !string.IsNullOrEmpty(tbName.Text) ? tbName.Text : string.Format("No name {0}", NewItem.ID);
					NewItem.Comment = !string.IsNullOrEmpty(tbComment.Text) ? tbComment.Text : "No comment";
				}
			}
		}
	}
}

Open in new window


Form2.Designer.cs -
namespace EE_Q28553270
{
	partial class Form2
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.lblID = new System.Windows.Forms.Label();
			this.tbID = new System.Windows.Forms.TextBox();
			this.tbName = new System.Windows.Forms.TextBox();
			this.lblName = new System.Windows.Forms.Label();
			this.tbComment = new System.Windows.Forms.TextBox();
			this.lblComment = new System.Windows.Forms.Label();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// lblID
			// 
			this.lblID.AutoSize = true;
			this.lblID.Location = new System.Drawing.Point(45, 9);
			this.lblID.Name = "lblID";
			this.lblID.Size = new System.Drawing.Size(21, 13);
			this.lblID.TabIndex = 0;
			this.lblID.Text = "ID:";
			// 
			// tbID
			// 
			this.tbID.Location = new System.Drawing.Point(72, 6);
			this.tbID.Name = "tbID";
			this.tbID.ReadOnly = true;
			this.tbID.Size = new System.Drawing.Size(200, 20);
			this.tbID.TabIndex = 1;
			// 
			// tbName
			// 
			this.tbName.Location = new System.Drawing.Point(72, 32);
			this.tbName.Name = "tbName";
			this.tbName.Size = new System.Drawing.Size(200, 20);
			this.tbName.TabIndex = 3;
			// 
			// lblName
			// 
			this.lblName.AutoSize = true;
			this.lblName.Location = new System.Drawing.Point(28, 35);
			this.lblName.Name = "lblName";
			this.lblName.Size = new System.Drawing.Size(38, 13);
			this.lblName.TabIndex = 2;
			this.lblName.Text = "Name:";
			// 
			// tbComment
			// 
			this.tbComment.Location = new System.Drawing.Point(72, 58);
			this.tbComment.Name = "tbComment";
			this.tbComment.Size = new System.Drawing.Size(200, 20);
			this.tbComment.TabIndex = 5;
			// 
			// lblComment
			// 
			this.lblComment.AutoSize = true;
			this.lblComment.Location = new System.Drawing.Point(12, 61);
			this.lblComment.Name = "lblComment";
			this.lblComment.Size = new System.Drawing.Size(54, 13);
			this.lblComment.TabIndex = 4;
			this.lblComment.Text = "Comment:";
			// 
			// btnOK
			// 
			this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.btnOK.Location = new System.Drawing.Point(116, 84);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(75, 23);
			this.btnOK.TabIndex = 6;
			this.btnOK.Text = "OK";
			this.btnOK.UseVisualStyleBackColor = true;
			this.btnOK.Click += new System.EventHandler(this.OnClick);
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(197, 84);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(75, 23);
			this.btnCancel.TabIndex = 7;
			this.btnCancel.Text = "Cancel";
			this.btnCancel.UseVisualStyleBackColor = true;
			this.btnCancel.Click += new System.EventHandler(this.OnClick);
			// 
			// Form2
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(284, 113);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.tbComment);
			this.Controls.Add(this.lblComment);
			this.Controls.Add(this.tbName);
			this.Controls.Add(this.lblName);
			this.Controls.Add(this.tbID);
			this.Controls.Add(this.lblID);
			this.Name = "Form2";
			this.Text = "Form2";
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Label lblID;
		private System.Windows.Forms.TextBox tbID;
		private System.Windows.Forms.TextBox tbName;
		private System.Windows.Forms.Label lblName;
		private System.Windows.Forms.TextBox tbComment;
		private System.Windows.Forms.Label lblComment;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Button btnCancel;
	}
}

Open in new window


DataItem.cs -
namespace EE_Q28553270
{
	public class DataItem
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public string Comment { get; set; }

		public DataItem() { ;}
	}
}

Open in new window


Also with a binding list, you only have to add and remove items from the list, the item (in this case a DataGridView) that the bindinglist is bound to will update automatically.

-saige-
Regarding your question - it is the t_user table.

Anyway Now the code look like this:
 private void button1_Click(object sender, EventArgs e)
        {
            

            PasssaveEntities db = new PasssaveEntities();
            var upd = (from u in db.t_Login where u.Id == u.Id select u).ToList();
            var bindingList = new BindingList<t_Login>(upd); // replace T with the type of upd
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;
    
        }

Open in new window


I would like to mention also how I fill the grid maybe it is not right. please look at the fill grid code.

public void Fill()
        {
            PasssaveEntities db = new PasssaveEntities();
            var fil = (from d in db.t_Login select new {d.Id, d.UserName, Password = "*******" });
            dataGridView1.DataSource = db.t_Login.ToList();

        }

Open in new window

OK so your LINQ query is returning a database table of some sort in which case your button1_Click would appear to be correct.  You may want to project your table results into some other object so that you can filter stuff out:

class User
{
    public string Id { get; set; }
}

private void button1_Click(object sender, EventArgs e)
{
    var db = new PasssaveEntities();
    var upd = (from u in db.t_Login where u.Id == u.Id select new User { Id = u.Id}).ToList(); // project table results to a User
    var bindingList = new BindingList<User>(upd);
    var dataSource = new BindingSource(bindingList, null);
    dataGridView1.DataSource = dataSource;
}

Open in new window


Why do you set the grids datasource in two different methods?  One is going to overwrite the other.
I do it because in that way - dataGridView1.DataSource = db.t_Login.ToList(); I can type into the grid and in this way dataGridView1.DataSource = fil.ToList(); i can't type into the grid.

Let me check the new code you sent me and let's see if it will work.

thanks .
I would like to show how I am loading the grid as well.

public frmcuser(string name)
        {
            InitializeComponent();
            label3.Text = name;
            txtpass.PasswordChar = '*';
            Fill();

        }

        //convert(varchar(6),userName)

        public void Fill()
        {
            PasssaveEntities db = new PasssaveEntities();
            var fil = (from d in db.t_Login select new {d.Id, d.UserName, Password = "*******" });
            dataGridView1.DataSource = db.t_Login.ToList();

        }

Open in new window

K I tried this one:

created new class:
public class loginuser
        {
            public int ID { get; set; }
            public string name { get; set; }
            public string password { get; set; }

        }

Open in new window


after I implemented the update button:
private void button1_Click(object sender, EventArgs e)
        {
            loginuser l = new loginuser();
            var db = new PasssaveEntities();
            var upd = (from u in db.t_Login where u.Id == u.Id select new loginuser { ID = u.Id, password = u.Password, name = u.UserName  }).ToList(); // project table results to a User
            var bindingList = new BindingList<loginuser>(upd);
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;
            dataGridView1.Update();
            dataGridView1.Refresh();
   
        }

after all this changes when I click on the update button it doesn't update the filed it just do nothing.
please see attachment in this case i changed NIcole name to something else and it didn't change.

thanks User generated image
That is because your update button is regenerating the bindingsource from the database call.

It looks like you want to be persisting your datagridview changes to your database in that button click event handler rather than retrieving the data again.
K, in my understanding I did the follow:

//update button
        private void button1_Click(object sender, EventArgs e)
        {
            
            loginuser l = new loginuser();
            var db = new PasssaveEntities();
            var upd = (from u in db.t_Login where u.Id == u.Id select new loginuser { ID = u.Id, password = u.Password, name = u.UserName  }).ToList(); // project table results to a User
            var bindingList = new BindingList<loginuser>(upd);
            var dataSource = new BindingSource(bindingList, null);
            dataGridView1.DataSource = dataSource;
            Fill();
            dataGridView1.Refresh();
    
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Vel Eous
Vel Eous

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
k, I found the way how to do it.

First of all thanks for all your help and suggestion and here is my solution:
All I have to do in order to update is to create int variable then call the method grid "fill"

int id = Convert.ToInt32(lblID.Text);
            string pas = SecurityUtil.SecurityUtil.EncryptMD5(txtpass.Text);
            PasssaveEntities db = new PasssaveEntities();
            var upd = ((from u in db.t_Login where u.Id == id select u)).FirstOrDefault();
            if (txtpass.Text != upd.Password)
                upd.Password = pas;
            upd.UserName = txtusern.Text;
            db.SaveChanges();
            Fill();

Open in new window