C#中的数据网格访问

3

我对c#和数据库连接不熟悉,因此无法通过搜索stackoverflow的旧帖子来获得这个。

类似代码

private void issueDetails()
    {
        string connectionPath = @"Data Source=Data\libraryData.dat;Version=3;New=False;Compress=True";

        using (SQLiteConnection connection = new SQLiteConnection(connectionPath))
        {
            SQLiteCommand command = connection.CreateCommand();
            connection.Open();
            string query = "SELECT bookno as 'Book No.',studentId as 'Student ID',  title as 'Title', author as 'Author', description as 'Description', issuedDate as 'Issued Date', dueDate as 'Due Date' FROM issuedBooks";
            command.CommandText = query;
            command.ExecuteNonQuery();

            SQLiteDataAdapter da = new SQLiteDataAdapter(command);
            DataSet ds = new DataSet();
            da.Fill(ds, "issuedBooks");
            dataGridView1.DataSource = ds.Tables["issuedBooks"];
            dataGridView1.Sort(dataGridView1.Columns["Student ID"], ListSortDirection.Ascending);
            dataGridView1.ReadOnly = true;
            connection.Close();
        }
    }

我曾使用上述代码来获取一些图书馆书籍的详细信息,例如借出日期和应还日期。现在,我想要突出显示一个特定的单元格,即超过了应还日期的单元格。
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        Color c = Color.Black;
        if (e.ColumnIndex == 6)
        {
            if (isLate(Convert.ToString(e.Value)))
            {
                c = Color.Red;
                count++;
                Console.WriteLine(count);
            }

        }
        e.CellStyle.ForeColor = c;
    }

    public string toInd(string date)
    {
        DateTimeFormatInfo fmt = new CultureInfo("fr-fr").DateTimeFormat;
        string dateString;
        DateTimeOffset offsetDate, dateig;
        string ret = DateTime.Now.ToShortDateString();
        dateString = date;
        bool ws = DateTimeOffset.TryParse(dateString, fmt, DateTimeStyles.None, out dateig);
        if (ws)
        {
            offsetDate = DateTimeOffset.Parse(dateString, fmt);
            ret = offsetDate.Date.ToShortDateString();
            return ret;
        }
        return ret;
    }

    private bool isLate(string nowS)
    {

        DateTime dueDate = Convert.ToDateTime(toInd(nowS));
        DateTime now;
        string present = DateTime.Now.ToShortDateString();
        now = Convert.ToDateTime(present);
        //Console.WriteLine(toInd(nowS));
        int a = dueDate.CompareTo(now);
        if (a >= 0)
            return false;
        else return true;
    }

但是如果使用if (isLate(Convert.ToString(e.Value))) { c = Color.Red; count++; Console.WriteLine(count); }来计算逾期的书籍数量,即使我的数据库中只有两本书过期,这个'count'值会增加4次,因为在数据绑定时这个if块被访问了2次,排序时又被访问了2次。我该如何得到仅逾期书籍数量的值?


1
你尝试过在select查询中按照学生ID对列表进行排序吗? - Aaron Ray
1
我试过了,但问题仍然存在... - Chandan Pasunoori
1
我在这里推测,也许 dataGridView1.ReadOnly = true; 触发了单元格格式化事件。你尝试过将其注释掉或者在绑定数据源之前放置它吗? - Aaron Ray
@Aaron Ray,我现在已经将它移除了,但问题仍然存在。 - Chandan Pasunoori
在CellFormatting事件中不应该进行任何计数。你无法控制基础设施可能调用它的次数。相反,在获取数据后,在将其绑定到网格之前找出哪些是过期的,然后在事件中仅检查行是否包含过期的书籍并进行格式化。 - Sergei Z
显示剩余3条评论
2个回答

2

实际上,dataGridView1_CellFormatting在每个单元格事件中都会触发,包括排序甚至悬停鼠标在单元格上。从性能方面来看,这非常昂贵。

相反,您可以使用dgv上的RowsAdded事件,该事件仅在添加时触发一次:

    private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        if (isLate(dataGridView1[6, e.RowIndex].Value.ToString()))
        {
            dataGridView1[0, e.RowIndex].Style.ForeColor = Color.Red;
            count++;
        }
    }

2

答案

private void UpdateDataGridViewColor()
    {
        if (calledMethod == 2)
        {
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                int j = 6;
                DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
                CellStyle.ForeColor = Color.Red;

                if (isLate(dataGridView1[j, i].Value.ToString()))
                {
                    dataGridView1[j, i].Style = CellStyle;
                }
            }
        }
    }

1
在窗体加载和 GridView 排序时使用此代码以获得正确的结果。 - Chandan Pasunoori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接