Question

I try to add some value to a dataGridView cell using C#. I have a column for each week day (Monday-Sunday). To do that I use this code:

xdoc.Load(Properties.Settings.Default.TaskPlannerXmlPath);

foreach (XmlNode task in xdoc.SelectNodes("/tasks/task"))
{
    string date = task["taskDate"].InnerText;
    string day = date.Substring(0, date.IndexOf(","));

    for (int w = 0; w < timeTableGridView.Columns.Count; w++)
    {
        string colName = timeTableGridView.Columns[w].Name;

        if (colName == day)
        {
            timeTableGridView.Rows.AddNew();

            for (int ew = 0; ew < timeTableGridView.Rows.Count; ew++)
            {
                timeTableGridView.Rows[ew].Cells[colName].Value = task["taskName"].InnerText;
            }
        }
    }
}

I read an XML file for getting the InnerText. My XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<tasks>
  <task>
    <taskName>test shutdown</taskName>
    <taskDate>Friday, 2. May 2014</taskDate>
    <taskTime>00:00</taskTime>
    <taskType>Shutdown</taskType>
  </task>

  <task>
    <taskName>test start</taskName>
    <taskDate>Sunday, 4. May 2014</taskDate>
    <taskTime>12:00</taskTime>
    <taskType>Wake Up</taskType>
  </task>
</tasks>

So now it should add in column "Friday" the text "test shutdown" and in column "Sunday" it should add "test start". But it doesn't. It adds "test shutdown" in column "Friday" and then it adds "test start" twice in column "Sunday".

I just don't get rid of it.

Any suggestions? :)

Était-ce utile?

La solution

That's because your loop

for (int w = 0; w < timeTableGridView.Columns.Count; w++)

iterates over every day of the week. If one of them is the same as the one you got from xml (which will always happen), you're adding a new row (what would that represent?) and then FOR EVERY ROW existing your setting up the task in a given day.

I think you may have some problems with understanding what and how would you represent in your datagridview. Right now data is redundant, since row with 7 columns will always use only 1 of them, while all others will be empty.

EDIT:

The thing is: you can't represent calendar in a datagridview this way (it's doable, but it'd be too difficult at this point). Assuming you want to do some kind of scheduler, your columns should be

Task Name, Date, Time and Type

and then each task from xml should be loaded as a row.

Autres conseils

Per your example, by the time you get to Sunday, you have already created two rows via calls to timeTableGridView.Rows.AddNew (one for Monday, and another one for Sunday). The following loop operates on the "sunday" column, but iterates twice because there are two rows:

for (int ew = 0; ew < timeTableGridView.Rows.Count; ew++)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top