показать самую последнюю дату просмотра данных - PullRequest
1 голос
/ 01 марта 2020

У меня есть сетка данных с колонкой, заполненной датами, я хочу, чтобы текстовое поле показывало только самую последнюю, что я сделал, чтобы поместить очень раннюю дату в текстовое поле (01/01/0000), а затем запустил вся сетка данных в a для l oop, но это дает мне эту ошибку

Строка не была распознана как действительный DateTime

 dataGridView1.Columns[14].DefaultCellStyle.Format = "dd/MM/yyyy";

        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            DateTime date = Convert.ToDateTime(dataGridView1.Rows[i].Cells[14].Value.ToString());
            DateTime date1 = DateTime.ParseExact(dataRecente.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
            if (date > date1)
            {
                dataRecente.Text = Convert.ToString(date);
            }
        }

Ответы [ 2 ]

0 голосов
/ 10 марта 2020

я нашел другое ... невероятно грубое и неопрятное решение, так как мне все равно, как выглядит интерфейс, и как нуб я знаю очень мало о наборе данных и т. Д. c я создал три таблицы данных с одним столбцом для первого дня на месяцы и один на годы. затем сценарий сортируется по годам, те, которые находятся сверху, с тем же годом go во втором просмотре сетки данных, и сортируются по месяцам, и сценарий повторяется для дня, в конце первая строка последних данных содержит самые последние свидание. Как сказано, это невероятно брути sh и может показаться неандертальским решением ... но это сработало.

 for (int i2 = 0; i2 < date.Rows.Count; i2++)
        {
            int inizio = Int32.Parse(date.Rows[i2].Cells[1].Value.ToString());
            int fine = Int32.Parse(date.Rows[i2].Cells[2].Value.ToString());
            for (int i = inizio; i < fine; i++)
            {
                dataSortingGrid.Rows.Add();
                int startIndex = 0;
                int length = 2;
                string dataIntera = dataGridView1.Rows[i].Cells[14].Value.ToString();
                int i3 = dataSortingGrid.Rows.Count - 1;
                String giorni = dataIntera.Substring(startIndex, length);
                dataSortingGrid.Rows[i3].Cells[0].Value = giorni;
                startIndex = 3;
                length = 2;
                String mesi = dataIntera.Substring(startIndex, length);
                dataSortingGrid.Rows[i3].Cells[1].Value = mesi;
                startIndex = 6;
                length = 4;
                String anni = dataIntera.Substring(startIndex, length);
                dataSortingGrid.Rows[i3].Cells[2].Value = anni;
                dataSortingGrid.Rows[i3].Cells[3].Value = dataGridView1.Rows[i].Cells[14].Value.ToString();
            }
            dataSortingGrid.Sort(dataSortingGrid.Columns[2], System.ComponentModel.ListSortDirection.Descending);
            //mesi

            int nRowMesi = Int32.Parse(dataSortingGrid.Rows.Count.ToString());
            for (int i = 0; i < nRowMesi; i++)
            {
                if (i < 1)
                {
                    dataSortingGridMesi.Rows.Add();
                    dataSortingGridMesi.Rows[i].Cells[0].Value = dataSortingGrid.Rows[i].Cells[0].Value;
                    dataSortingGridMesi.Rows[i].Cells[1].Value = dataSortingGrid.Rows[i].Cells[1].Value;
                    dataSortingGridMesi.Rows[i].Cells[2].Value = dataSortingGrid.Rows[i].Cells[2].Value;
                    dataSortingGridMesi.Rows[i].Cells[3].Value = dataSortingGrid.Rows[i].Cells[3].Value;

                }
                else
                {
                    int valoreAnniSopra = Convert.ToInt32(dataSortingGrid.Rows[i - 1].Cells[2].Value);
                    int valoreAnniSotto = Convert.ToInt32(dataSortingGrid.Rows[i].Cells[2].Value);
                    if (valoreAnniSotto < valoreAnniSopra)
                    {
                        break;
                    }
                    dataSortingGridMesi.Rows.Add();

                    dataSortingGridMesi.Rows[i].Cells[0].Value = dataSortingGrid.Rows[i].Cells[0].Value;
                    dataSortingGridMesi.Rows[i].Cells[1].Value = dataSortingGrid.Rows[i].Cells[1].Value;
                    dataSortingGridMesi.Rows[i].Cells[2].Value = dataSortingGrid.Rows[i].Cells[2].Value;
                    dataSortingGridMesi.Rows[i].Cells[3].Value = dataSortingGrid.Rows[i].Cells[3].Value;

                }
            }
            dataSortingGridMesi.Sort(dataSortingGridMesi.Columns[1], System.ComponentModel.ListSortDirection.Ascending);

            //giorni

            int nRowGiorni = Int32.Parse(dataSortingGridMesi.Rows.Count.ToString());
            for (int i = 0; i < nRowGiorni; i++)
            {
                if (i < 1)
                {
                    dataSortingGridGiorni.Rows.Add();
                    dataSortingGridGiorni.Rows[i].Cells[0].Value = dataSortingGridMesi.Rows[i].Cells[0].Value;
                    dataSortingGridGiorni.Rows[i].Cells[1].Value = dataSortingGridMesi.Rows[i].Cells[1].Value;
                    dataSortingGridGiorni.Rows[i].Cells[2].Value = dataSortingGridMesi.Rows[i].Cells[2].Value;
                    dataSortingGridGiorni.Rows[i].Cells[3].Value = dataSortingGridMesi.Rows[i].Cells[3].Value;

                }
                else
                {
                    int valoreMesiSopra = Convert.ToInt32(dataSortingGridMesi.Rows[i - 1].Cells[1].Value);
                    int valoreMesiSotto = Convert.ToInt32(dataSortingGridMesi.Rows[i].Cells[1].Value);
                    if (valoreMesiSotto < valoreMesiSopra)
                    {
                        break;
                    }
                    dataSortingGridGiorni.Rows.Add();

                    dataSortingGridGiorni.Rows[i].Cells[0].Value = dataSortingGridMesi.Rows[i].Cells[0].Value;
                    dataSortingGridGiorni.Rows[i].Cells[1].Value = dataSortingGridMesi.Rows[i].Cells[1].Value;
                    dataSortingGridGiorni.Rows[i].Cells[2].Value = dataSortingGridMesi.Rows[i].Cells[2].Value;
                    dataSortingGridGiorni.Rows[i].Cells[3].Value = dataSortingGridMesi.Rows[i].Cells[3].Value;

                }
            }
            dataSortingGridGiorni.Sort(dataSortingGridGiorni.Columns[0], System.ComponentModel.ListSortDirection.Descending);
0 голосов
/ 01 марта 2020

Почему бы не получить дату прямо из источника для datagridview, предположительно datatable или dataset? Если базовые данные изменяются позже, например, из-за ввода пользователя, таблица данных может вызвать событие , поэтому вы можете обновить sh текстовое поле.

Значение l oop совершенно не нужно Так же как и разбор и преобразование. Если у вас есть допустимые значения даты и времени, они могут быть легко отсортированы.

Кроме того, вы предполагаете, что дата всегда будет в определенном столбце, но пользователь может перетаскивать столбцы и изменять порядок отображения, и ваш код будет sh несчастно.

Таким образом, вместо:

dataGridView1.Columns[14].DefaultCellStyle.Format = "dd/MM/yyyy";

вы можете иметь:

dataGridView1.Columns[datagridview1.Columns["colDate"].Index].DefaultCellStyle.Format = "dd/MM/yyyy";

(не проверено, но должно быть очень близко, если не правильно)

Каждый столбец в таблице данных является элементом управления , и, надеюсь, вы дали им значимых имен столбцов (в данном примере: colDate).

Вы можете извлечь максимальную дату из таблицы данных с помощью функции DataTable.Compute , например:

table.Compute("MAX([DateColumn 1])", "");

(Обработайте случай, когда таблица данных пуста, или ожидайте, что возвращаемое значение будет быть нулевым)

Другие альтернативы: используйте функцию DataTable.Select или LINQ .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...