Solved

How to loop through a windows forms datagrid

Posted on 2014-09-25
21
219 Views
Last Modified: 2014-09-26
I have a System.Windows.Forms.Datagrid that in want to loop though to update the data.

 private System.Windows.Forms.DataGrid dataGridUrl;

The help system says there is an "Items" property, but when I try and access it I get a compile error "'System.Windows.Forms.DataGrid' does not contain a definition for 'Item' ...."

I am trying to:

foreach( (DataGridItem item in dataGridUrl.Item)
{
}

What am I missing?
0
Comment
Question by:No1Coder
  • 10
  • 10
21 Comments
 
LVL 8

Expert Comment

by:Ganapathi
Comment Utility
Spelling mistake I guess. It should be "Items".
foreach(DataGridItem item in dataGridUrl.Items)
{
}

Open in new window

0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
one easy way is to loop through the datasource of the grid:

private void PrintCellValues(DataGrid myGrid){
int iRow;
int iCol;
DataTable myTable;
// Assumes the DataGrid is bound to a DataTable.
myTable = (DataTable) dataGrid1.DataSource;
for(iRow = 0;iRow < myTable.Rows.Count ;iRow++) {
for(iCol = 0;iCol < myTable.Columns.Count ;iCol++) {
Console.WriteLine(myGrid[iRow, iCol]);
}
}
}

Open in new window

0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
or loop through the rows of the grid:

foreach (DataGridViewRow row in dgvDataGridView.Rows)
{
    (row.Cells[0]).Value = "something";
}

Open in new window

0
 

Author Comment

by:No1Coder
Comment Utility
If I type in data in one of the fields in the grid, the loop through, the data is not updated. I get the original value.  How do I "accept changes"?
0
 

Author Comment

by:No1Coder
Comment Utility
Also, one of the columns in the grid is a checkbox.  How do I read the state of the checkbox?

object col1 = dataGridUrl[0][1];  // this is a checkbox column

What is the object?
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
Strange. Have you tried both methods? Can you show your code?
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
have you tried something like:
foreach (DataGridViewRow row in dgvDataGridView.Rows)
{
    ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
}

Open in new window

0
 

Author Comment

by:No1Coder
Comment Utility
I am simply trying to update the underlying table that the data grid is bound to.  One would thing there would be a standard method for doing this, but I can't find it.  

I am using a DataGrid.  Not a DataGridView.

           DataTable urls = ds["urls"];  // get table from data set
           int iRow, iCol;
            for (iRow = 0; iRow < urls.Rows.Count; iRow++)
            {
                object o = dataGridUrl[iRow, 0];   // this gets the original string value, not the value I type into the grid
                object o1 = dataGridUrl[iRow, 1]; // this returns an object but I don't know what it is.  Checkbox column
                urls.Rows[iRow]["url"] = o;
                urls.Rows[iRow]["disable"] = o1;
            }
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
I just created a sample and it is working for me:

 
       private DataTable _dt;

        private void Form1_Load(object sender, EventArgs e)
        {

            _dt = new DataTable("test");

            _dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
            _dt.Columns.Add(new DataColumn("Name", typeof (string)));
            _dt.Columns.Add(new DataColumn("Selected", typeof(bool)));

            dataGrid1.DataSource = _dt;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (DataRow row in _dt.Rows)
            {
                int id = Convert.ToInt32(row["ID"].ToString());
                string name = row["Name"].ToString();
                bool selected = Convert.ToBoolean(row["Selected"].ToString());
                int i = 0;
            }
        }

Open in new window

0
 

Author Comment

by:No1Coder
Comment Utility
Your code is reading from a table, not the grid.  I am trying to update a table from a grid, where the user types in information.  It doesn't appear to happen automatically.  If I just enter data in a grid field, and don't click anything on the grid, and then I save the underlying table from a button click, it does not have the updated data.  That is why I am trying to loop through the grid, so I can manually update the table.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
>>Your code is reading from a table, not the grid

Try it. The grid is bound to the datatable so the content of the datatable is in sync with the grid
0
 

Author Comment

by:No1Coder
Comment Utility
Will you explain the theory behind this code?  It doesn't make any sense to me.

Looks to me like it is just reading fields from the table.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
the content of the grid is bound to the datatable. it is not a copy, it is a reference. so if you modify the datatable and/or the datagrid, the other one should be updated.
0
 

Author Comment

by:No1Coder
Comment Utility
Okay, but...

I enter data into a field on the grid, and click an update link.  The update saves the dataset to an xml file. The data entered into the field is not saved. The original data is saved.
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
Have you tried my sample? When you click the button, it shows the new value you entered!
0
 

Author Comment

by:No1Coder
Comment Utility
Will try tomorrow but i dont understany why reading the datatable will fix my issue.
0
 

Author Comment

by:No1Coder
Comment Utility
I tried and it didn't work.

The grid has an entry field.  I type in data, hit my save button, and the screen reverts back to the original value.

If I make a change to the field, and then add another row, and then click save, it does save the value.

I think something happens when the row changes to "accept the text".
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
does your table have a primary key?

can you provide a sample?
0
 

Author Comment

by:No1Coder
Comment Utility
No, it doesn't.  It is not a sql table.  Just a manually created table that gets stored as an xml file.

I discovered something about the grid.  When I type data in a cell, the row indicator changed from a "carat" character, to a "pencil" character.  If after typing in data, I click the Pencil icon, it saves the data to the data table.

I guess that is the way it works, but doesn't see very intuitive for users.  Can I programmically switch from edit mode back to normal, and thereby cause the entry to be accepted.
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 500 total points
Comment Utility
your row is not committed. You need to call EndEdit. Check http://bytes.com/topic/c-sharp/answers/246058-saving-changes-datagrid-one-row
0
 

Author Comment

by:No1Coder
Comment Utility
Thanks
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This article describes how to add a user-defined command button to the Windows 7 Explorer toolbar.  In the previous article (http://www.experts-exchange.com/A_2172.html), we saw how to put the Delete button back there where it belongs.  "Delete" is …
If you have ever found yourself doing a repetitive action with the mouse and keyboard, and if you have even a little programming experience, there is a good chance that you can use a text editor to whip together a sort of macro to automate the proce…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now