How to loop through a windows forms datagrid

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?
No1CoderAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GanapathiFacets DeveloperCommented:
Spelling mistake I guess. It should be "Items".
foreach(DataGridItem item in dataGridUrl.Items)
{
}

Open in new window

0
Éric MoreauSenior .Net ConsultantCommented:
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
Éric MoreauSenior .Net ConsultantCommented:
or loop through the rows of the grid:

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

Open in new window

0
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

No1CoderAuthor Commented:
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
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
Strange. Have you tried both methods? Can you show your code?
0
Éric MoreauSenior .Net ConsultantCommented:
have you tried something like:
foreach (DataGridViewRow row in dgvDataGridView.Rows)
{
    ((DataGridViewCheckBoxCell)row.Cells[0]).Value = true;
}

Open in new window

0
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
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
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
>>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
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
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
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
Have you tried my sample? When you click the button, it shows the new value you entered!
0
No1CoderAuthor Commented:
Will try tomorrow but i dont understany why reading the datatable will fix my issue.
0
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
does your table have a primary key?

can you provide a sample?
0
No1CoderAuthor Commented:
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
Éric MoreauSenior .Net ConsultantCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
No1CoderAuthor Commented:
Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.