9 Replies - 2205 Views - Last Post: 30 August 2012 - 12:31 AM Rate Topic: -----

#1 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Populate datagridview :(

Posted 29 August 2012 - 11:16 AM

Hello.

I'm having problem populating my datagridview with data from a List<T>.

First i programmatically add my columns at the formloading method with this method:

        /// <summary>
        /// Set's the column and add rows to datagrid
        /// </summary>
        public void LoadDataGridView()
        {


            DataGridViewColumn col1 = new DataGridViewTextBoxColumn();
            col1.HeaderText = "Träningsrörelse";
            int colIndex1 = dataGridView1.Columns.Add(col1);

            DataGridViewColumn col2 = new DataGridViewTextBoxColumn();
            col2.HeaderText = "kg/reps";
            int colIndex2 = dataGridView1.Columns.Add(col2);

            DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
            col3.HeaderText = "kg/reps";
            int colIndex3 = dataGridView1.Columns.Add(col3);

            DataGridViewColumn col4 = new DataGridViewTextBoxColumn();
            col4.HeaderText = "kg/reps";
            int colIndex4 = dataGridView1.Columns.Add(col4);

            DataGridViewColumn col5 = new DataGridViewTextBoxColumn();
            col5.HeaderText = "kg/reps";
            int colIndex5 = dataGridView1.Columns.Add(col5);

            DataGridViewColumn col6 = new DataGridViewTextBoxColumn();
            col6.HeaderText = "kg/reps";
            int colIndex6 = dataGridView1.Columns.Add(col6);

            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
            dataGridView1.Rows.Add();
        }



If I have three buttons on my Windows Form (and of course the datagridview) one named "Clear", one named "Load" and one named "Save".
The save button method is this one:

        /// <summary>
        /// Save datagrid to list. Loop through every row.
        /// </summary>
        public void SaveDatagrid()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                Movements content = new Movements();
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    // Has to make this check otherwise it crashes if one row is empty
                    string strValue = dataGridView1[j, i].Value == null ? string.Empty : dataGridView1[j, i].Value.ToString();

                    if (j == 0)
                        content.Exercise = strValue;
                    else if (j == 1)
                        content.KgReps1 = strValue;
                    else if (j == 2)
                        content.KgReps2 = strValue;
                    else if (j == 3)
                        content.KgReps3 = strValue;
                    else if (j == 4)
                        content.KgReps4 = strValue;
                    else if (j == 5)
                        content.KgReps5 = strValue;
                }
                m_moveList.Add(content);

            }


My class "Movements" cotains private string varibles for each column with propertys for each varible. Over each property I have the following code to show the name when I load the datagridview:
[System.ComponentModel.DisplayName("Here is the column name")]


My Load method is this only this line:
dataGridView1.DataSource = m_moveList;


And to clear the datagridview I use this line of code:
dataGridView1.Columns.Clear();



Now, if I put in data when I while I run my program, press the save button, then the clear button, the the load button. It all works like a charm!

But when I want to save and then clear AND load at the same time with this two lines together:

dataGridView1.Columns.Clear();

dataGridView1.DataSource = m_moveList;


It doesn't work! It only shows the column names not even empty rows. There is none rows. How can I make it work?
The thing is I have a second form where I want to press an Edit button and then populate the form were I have the datagridview. But when I try to load the datagridview with :
dataGridView1.DataSource = m_moveList;

I get the same error, only the column name shows, not even one row.

I would really like some input on this! :)
I have googled my as off and check Microsoft helppages but I really can't solve this problem alone. :/

Best regards
Robert a.k.a Cyrix

Is This A Good Question/Topic? 0
  • +

Replies To: Populate datagridview :(

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6536
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Populate datagridview :(

Posted 29 August 2012 - 11:25 AM

Quote

Now, if I put in data when I while I run my program, press the save button, then the clear button, the the load button. It all works like a charm!


Then show us all three methods for those that work, and the complete method for the one that doesn't. a couple isolated lines doesn't help us diagnose the difference in behavior.

Quote

Now, if I put in data when I while I run my program, press the save button, then the clear button, the the load button. It all works like a charm!


Then show us all three methods for those that work, and the complete method for the one that doesn't. a couple isolated lines doesn't help us diagnose the difference in behavior.
Was This Post Helpful? 0
  • +
  • -

#3 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Re: Populate datagridview :(

Posted 29 August 2012 - 11:32 AM

View PosttlhIn`toq, on 29 August 2012 - 11:25 AM, said:

Quote

Now, if I put in data when I while I run my program, press the save button, then the clear button, the the load button. It all works like a charm!


Then show us all three methods for those that work, and the complete method for the one that doesn't. a couple isolated lines doesn't help us diagnose the difference in behavior.

Quote

Now, if I put in data when I while I run my program, press the save button, then the clear button, the the load button. It all works like a charm!


Sorry for my english. :>
But actually the method only contains one line of code each but to be correct the methods that do work are as follow:

  /// <summary>
        /// Clear the datagrid
        /// </summary>
        public void ClearDataGrid()
        {
            dataGridView1.Columns.Clear();
        }



and:

        /// <summary>
        /// Load datagrid with values
        /// </summary>
        public void LoadDatagrid()
        {
            dataGridView1.DataSource = m_moveList;
        }



and the save method I paste in my first post.

Thank you for trying. :)

Best regards
Cyrix
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7219
  • View blog
  • Posts: 24,482
  • Joined: 05-May 12

Re: Populate datagridview :(

Posted 29 August 2012 - 01:28 PM

DataGridView.Columns.Clear() removes all those columns you added. That is not the correct way to clear a DataGridView.

I'm not seeing where you are setting the DataPropertyName property for each of your columns. But the result of that should have been empty columns but N number of rows.

The following code correctly binds to a List when you press the Bind button.

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;
using System.Globalization;

namespace SimpleWinForms
{
    public partial class Form1 : Form
    {
        DataGridView _dgv = new DataGridView();
        List<Hero> _heroes = new List<Hero>();

        public Form1()
        {
            // InitializeComponent();

            var tlp = new TableLayoutPanel();
            tlp.Dock = DockStyle.Fill;
            tlp.AutoSize = true;

            var nameColumn = new DataGridViewTextBoxColumn();
            nameColumn.HeaderText = "Name";
            nameColumn.DataPropertyName = "Name";

            var identityColumn = new DataGridViewTextBoxColumn();
            identityColumn.HeaderText = "Secret Identity";
            identityColumn.DataPropertyName = "SecretIdentity";

            _dgv.Dock = DockStyle.Fill;
            _dgv.AutoSize = true;
            _dgv.AutoGenerateColumns = false;
            _dgv.AllowUserToAddRows = false;
            _dgv.Columns.Add(nameColumn);
            _dgv.Columns.Add(identityColumn);

            var btnLoad = new Button();
            btnLoad.Text = "Load";
            btnLoad.Click += (obj, e) => _dgv.DataSource = _heroes;

            tlp.Controls.Add(btnLoad);
            tlp.Controls.Add(_dgv);

            Controls.Add(tlp);

            _heroes.Add(new Hero("Superman", "Clark Kent"));
            _heroes.Add(new Hero("Batman", "Bruce Wayne"));
        }
    }

    public class Hero
    {
        public string Name { get; set; }
        public string SecretIdentity { get; set; }

        public Hero(string name, string identity)
        {
            Name = name;
            SecretIdentity = identity;
        }
    }
}


Was This Post Helpful? 1
  • +
  • -

#5 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Re: Populate datagridview :(

Posted 29 August 2012 - 01:47 PM

View PostSkydiver, on 29 August 2012 - 01:28 PM, said:

DataGridView.Columns.Clear() removes all those columns you added. That is not the correct way to clear a DataGridView.

I'm not seeing where you are setting the DataPropertyName property for each of your columns. But the result of that should have been empty columns but N number of rows.

The following code correctly binds to a List when you press the Bind button.

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;
using System.Globalization;

namespace SimpleWinForms
{
    public partial class Form1 : Form
    {
        DataGridView _dgv = new DataGridView();
        List<Hero> _heroes = new List<Hero>();

        public Form1()
        {
            // InitializeComponent();

            var tlp = new TableLayoutPanel();
            tlp.Dock = DockStyle.Fill;
            tlp.AutoSize = true;

            var nameColumn = new DataGridViewTextBoxColumn();
            nameColumn.HeaderText = "Name";
            nameColumn.DataPropertyName = "Name";

            var identityColumn = new DataGridViewTextBoxColumn();
            identityColumn.HeaderText = "Secret Identity";
            identityColumn.DataPropertyName = "SecretIdentity";

            _dgv.Dock = DockStyle.Fill;
            _dgv.AutoSize = true;
            _dgv.AutoGenerateColumns = false;
            _dgv.AllowUserToAddRows = false;
            _dgv.Columns.Add(nameColumn);
            _dgv.Columns.Add(identityColumn);

            var btnLoad = new Button();
            btnLoad.Text = "Load";
            btnLoad.Click += (obj, e) => _dgv.DataSource = _heroes;

            tlp.Controls.Add(btnLoad);
            tlp.Controls.Add(_dgv);

            Controls.Add(tlp);

            _heroes.Add(new Hero("Superman", "Clark Kent"));
            _heroes.Add(new Hero("Batman", "Bruce Wayne"));
        }
    }

    public class Hero
    {
        public string Name { get; set; }
        public string SecretIdentity { get; set; }

        public Hero(string name, string identity)
        {
            Name = name;
            SecretIdentity = identity;
        }
    }
}



Thank you for your reply.
I didn't have dataproperty name, but it doesn't mather becase even if I have, it would be the same problem.
In my example that actually work I have to user that column.clear method becase otherwise it duplicates the columns. But if I use it on my actually project with two simple forms then I don't need colum.clear method. I can just try (!) to update with
datagridview.DataSource = myList; 


And when I do, I still get the same problem. The information in my saved list (and I'm sure the list got saved values) doesn't update my datagridview. The only thing that happens is that my column name shows without any (!) rows.

I would like how I can update/populate my datagridview from my List<T>. It's strange that I can't get it to work. It seems to be so simple. :P

Thank you for your reply!

Best regards
Cyrix
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7219
  • View blog
  • Posts: 24,482
  • Joined: 05-May 12

Re: Populate datagridview :(

Posted 29 August 2012 - 01:49 PM

The duplicate columns indicates that you did not set AutogenerateColumns to false.
Was This Post Helpful? 1
  • +
  • -

#7 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Re: Populate datagridview :(

Posted 29 August 2012 - 01:55 PM

View PostSkydiver, on 29 August 2012 - 01:49 PM, said:

The duplicate columns indicates that you did not set AutogenerateColumns to false.


Oh, your right. That meens that I don't need to clear the columns. But I tested and I still can't load my datagridview, same problem. Only columns headers name show and no rows. :/

Best regards
Cyrix
Was This Post Helpful? 0
  • +
  • -

#8 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7219
  • View blog
  • Posts: 24,482
  • Joined: 05-May 12

Re: Populate datagridview :(

Posted 29 August 2012 - 01:58 PM

I have a sneaking suspicion your list maybe empty at the time you hit this line of code:
datagridview.DataSource = m_movementList; 



Set a breakpoint and inspect m_movementList to make sure that it not empty.

If it is not empty, then change the code to:
datagridview.DataSource = null;
datagridview.DataSource = m_movementList; 


Was This Post Helpful? 1
  • +
  • -

#9 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Re: Populate datagridview :(

Posted 29 August 2012 - 02:03 PM

View PostSkydiver, on 29 August 2012 - 01:58 PM, said:

I have a sneaking suspicion your list maybe empty at the time you hit this line of code:
datagridview.DataSource = m_movementList; 



Set a breakpoint and inspect m_movementList to make sure that it not empty.

If it is not empty, then change the code to:
datagridview.DataSource = null;
datagridview.DataSource = m_movementList; 



Oops, it was empty. Haha, darn!
We are coming closer to the truth..
Weird that it save to the list when i try to save when I have my form open (checked, then my list has values/the items) but when I exit the form and use the exact same method it doesn't. Hmm.

Best regards
Cyrix
Was This Post Helpful? 0
  • +
  • -

#10 cyrix83   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 29-August 12

Re: Populate datagridview :(

Posted 30 August 2012 - 12:31 AM

Thank you Skydiver, you were most helful!
I finally solved my problem after many, many hours of trying.
You made me realize that the problem were trying to solve wasn't the real problem. The problem was how I was trying to save my list.
Everytime I closed my childform all saved content was gone. So I created the List<T> in another class and made it to a property with set and get. Then the trick was to make one of the accessmodifiers to static when I declared the instance of the class.

Here is the code in my form class:

        private static DiaryManager objTest = new DiaryManager();
        private List<Movements> testList = objTest.MovementsList;


I was just testing that's why I used thoose names. But now it's working.

Thank you again!

Best regards
Cyrix :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1