[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C# -- DataGridView -- LOOP Updating ?

Posted on 2009-12-18
6
Medium Priority
?
627 Views
Last Modified: 2013-12-17
How can change the below so the testing1 
variable works during my DataGridView update ?
  ** screenshot attached

Basically I need some type of loop statement to get the
correct this.dataGridViewTextBoxColumn4.ToString();
VALUE during updating.
-------------------------------------------------------------------------------------
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            this.Validate();
            decimal iGML_ROMSTR_ID = 0;
            try
            {
                DataSet1TableAdapters.GML_SEQ_ROMSTRTableAdapter_ adpSeq = new MenuByUser.DataSet1TableAdapters.GML_SEQ_ROMSTRTableAdapter_();
                DataSet1.GML_SEQ_ROMSTRDataTable tb = adpSeq.GetData();

                if (tb != null && tb.Rows.Count > 0)
                {
                    if (tb.Rows[0][0] != DBNull.Value)
                    {
                        iGML_ROMSTR_ID = Convert.ToDecimal(tb.Rows[0][0]);
                    }
                }
                if (iGML_ROMSTR_ID <= 0)
                    iGML_ROMSTR_ID = 1;

                string testing1 = String.Empty;
                testing1 = this.dataGridViewTextBoxColumn4.ToString();
                //below inserts locnum-itemID-pallets-pri-date-user-RO#-vend#
                this.gML_ROITEMTableAdapter.InsertQuery(25, 177982, 888, null, DateTime.Today, 42, iGML_ROMSTR_ID, Convert.ToDecimal(this.cboVendor.SelectedValue.ToString()));
                //this.gML_ROITEMTableAdapter.InsertQuery(25, 177982, testing1, null, DateTime.Today, 42, iGML_ROMSTR_ID, Convert.ToDecimal(this.cboVendor.SelectedValue.ToString()));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Assign Error-> " + ex.Message);
            }
        }

0002.jpg
0
Comment
Question by:finance_teacher
  • 3
  • 2
6 Comments
 
LVL 3

Expert Comment

by:MikeDotNet555
ID: 26083594
You want to get all values of PALLETSREQ column? I am not sure what is exactly your question some clarification could help.
0
 

Author Comment

by:finance_teacher
ID: 26083657
I have an input DataGridView FORM and need the following to work:
 1. user enters 20 lines of info
 2. user clicks "Submit"
 3. each line gets COMMITED to database

Currently I have three
column values working
  DateTime.Today
  iGML_ROMSTR_ID
  Convert.ToDecimal(this.cboVendor.SelectedValue.ToString())
------------------------------------------------------------------------------------
I need to get the other values (dataGridViewTextBoxColumn4/etc) working
which is easily doable via the below, but cannot be done this way since
I am passing the above three values
            this.Validate();
            this.gML_ROITEMBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.dataSet1);
------------------------------------------------------------------------------------
Please help
0
 
LVL 3

Expert Comment

by:MikeDotNet555
ID: 26084572
I don't really understand what is preventing you from getting the values but wouldn't it be better to deal with the datasource directly?
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 

Author Comment

by:finance_teacher
ID: 26084624
It might be better, I am new and still learning.

Please post an example.

Thanks ...
0
 
LVL 3

Expert Comment

by:MikeDotNet555
ID: 26084907
Well the base idea is to get a collection that you will DataBind to your DataGridView. It is preferable to use a BindingList instead of a list since you can implement the INotifyPropertyChanged interface so if you make change programatically to fields in your object being in the collection it is immidiately reflected in the datagridview.

What I like to do is a custom class that can track changes so you only need to updates the rows that changed (not sure how dataset works, but linq-to-sql can be a bit nasty). You can drop that part if needed but I will still explain.

So I start by implementing System.ComponentModel.INotifyPropertyChanged to my class, and each property that have a set accessor raise the event. I also make a call to my ChangeState() function within the set accessor (see code1).

The onPropertyChanged is simply used to call the event (see code 2)

I use several states (Code3) to keep track of changes/new/deleted  items.

You then only change the state to Changed if the current state is equal to Unchanged (Code4)

I then have a static method withing that class (it will let you access private properties) to save the collection. Here I use datacontext but you could probably modify it to use a datatable instead. (Code5)

That is for the editing part, now when you retrieve values from the database you generate a collection of your custom objects, using System.ComnentModel.BindingList instead of List. This is a very straightforward process, just make a private constructor that accept a database object and you are good to go (Code6)

All the code below should be in the same class. After that you can get the collection from your windows form by calling the GetAll() method (Code7) and bind it to your datagridview (Code8)

Then if you don't want a mid-class to do the binding stuff, you can cast your datasource to ienumerable<T> and pass this to your Save method.

There are a few things to note:
-The colums that will be displayed in the datagridview are the properties that have a public get accessor (if you do internal int myInt{get{//}} it will not show up, they must be public).
-The colums that will be editable by the users are the properties that fill the requirement below and that have a set accessor (Like OrderId in my code snippet is modifiable, remove the set accessor and it is not).
-Your collection will be modified automatically as user edit the datagridview (there is no extra steps necessary)
-Be sure to reset all states to unchanged once you are done with a save operation
-You can of course bind your datagridview directly to your database object but I had endless problems doing that so I opted for a disconnected architecture.

I hope that help, I am practicing writing articles so even if you don't like my idea it's been really nice to write this down.

Don't hesitate to ask more questions if you have any (or if you would like to go another route).
code 1 
public int? OrderId
        {
            get
            {
                return this.orderId;
            }
            set
            {
                this.orderId = value;
                ChangeState();
                onPropertyChanged("OrderId");
            }
        }

code2
protected void onPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }

code3
    internal enum CdKeyInfoState
    {
        Unchanged,
        New,
        Changed,
        DeleteRequested,
    }

Code4
        private void ChangeState()
        {
            if (state == CdKeyInfoState.Unchanged)
                state = CdKeyInfoState.Changed;
        }

Code5
public static void SaveAll(IEnumerable<CdKeyInfo> cdkeys)
        {
            using (var context = NewContext)
            {
                foreach (var cdkey in cdkeys)
                {
                    if (cdkey.state == CdKeyInfoState.Changed)
                    {
                        //modify an existing record
                    }
                    else if (cdkey.state == CdKeyInfoState.New)
                    {
                        //add a new record
                    }
                    else if (cdkey.state == CdKeyInfoState.DeleteRequested)
                    {
                        //Delete the record
                    }
                }
                context.SubmitChanges();
            }
        }

Code6
 public static IEnumerable<CdKeyInfo> GetAll()
        {
            List<CdKeyInfo> retVal = new List<CdKeyInfo>();
            using (var context = NewContext)
            {
                var allKeys = (from k in context.tblCdKeyDeliveries select k);
                foreach (var key in allKeys)
                {
                    retVal.Add(new CdKeyInfo(key));
                }
            }
            return retVal;
        }

Code7
IEnumerable<CdKeyInfo> rawKeys = CdKeyInfo.GetAll();
            List<CdKeyInfo> keyList = new List<CdKeyInfo>(rawKeys);
 return new BindingList<CdKeyInfo>(cdKeys.OrderBy(n => n.DeliverDate).ToList());

Code8
this.dgvCdKeys.DataSource = CdKeyBinder.GetNewBindingList();

Open in new window

0
 
LVL 15

Accepted Solution

by:
rajeeshmca earned 2000 total points
ID: 26085997
Hii finance_teacher

Try the following code

string testing1 = String.Empty;
            for (int i = 0; i <= dataGridView1.Rows.Count - 2; i++)
            {
                testing1 = this.dataGridView1["dataGridViewTextBoxColumn4", i].Value.ToString();
                this.gML_ROITEMTableAdapter.InsertQuery(25, 177982, testing1, null, DateTime.Today, 42, iGML_ROMSTR_ID, Convert.ToDecimal(this.cboVendor.SelectedValue.ToString()));
            }
 
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Loops Section Overview
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question