Solved

How to loop through a windows forms datagrid

Posted on 2014-09-25
21
225 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
ID: 40343699
Spelling mistake I guess. It should be "Items".
foreach(DataGridItem item in dataGridUrl.Items)
{
}

Open in new window

0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 40343708
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 70

Expert Comment

by:Éric Moreau
ID: 40343711
or loop through the rows of the grid:

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

Open in new window

0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 

Author Comment

by:No1Coder
ID: 40343755
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
ID: 40343765
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 70

Expert Comment

by:Éric Moreau
ID: 40343769
Strange. Have you tried both methods? Can you show your code?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 40343777
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
ID: 40343799
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 70

Expert Comment

by:Éric Moreau
ID: 40343860
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
ID: 40343995
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
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 40344015
>>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
ID: 40345185
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 70

Expert Comment

by:Éric Moreau
ID: 40345189
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
ID: 40345200
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 70

Expert Comment

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

Author Comment

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

Author Comment

by:No1Coder
ID: 40345256
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 70

Expert Comment

by:Éric Moreau
ID: 40345687
does your table have a primary key?

can you provide a sample?
0
 

Author Comment

by:No1Coder
ID: 40345769
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 70

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 40345822
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
ID: 40345989
Thanks
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

After several hours of googling I could not gather any information on this topic. There are several ways of controlling the USB port connected to any storage device. The best example of that is by changing the registry value of "HKEY_LOCAL_MACHINE\S…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
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…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

828 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