Visual Studio 如何手动设置datagridview列上两个日期之间的数据?

scyqe7ek  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(85)

enter image description here
我有一个datagridview,它有两个日期列,名为:“收到SOA”和“支付日期”。我想做的是计算差异并在列名“NO”上显示结果。付款天数”

nhaq1z21

nhaq1z211#

要手动设置“否”上的数据,请执行以下操作:根据“SOA RECEIVED”和“DATE PAID”列,可以使用DataGridView控件的CellFormatting事件。此事件允许您自定义网格中数据的显示。以下是如何在C#中实现这一点的分步指南:
1.订阅DataGridViewCellFormatting事件。您可以在设计器或代码中执行此操作:

dataGridView1.CellFormatting += DataGridView1_CellFormatting;

字符串
1.实现CellFormatting事件处理程序:

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // Check if we are formatting the "NO. OF DAYS PAID" column
    if (dataGridView1.Columns[e.ColumnIndex].Name == "NO. OF DAYS PAID")
    {
        // Check if the current row is not a header row and has data in "SOA RECEIVED" and "DATE PAID" columns
        if (e.RowIndex >= 0 &&
            dataGridView1.Rows[e.RowIndex].Cells["SOA RECEIVED"].Value != null &&
            dataGridView1.Rows[e.RowIndex].Cells["DATE PAID"].Value != null)
        {
            DateTime soaReceived = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["SOA RECEIVED"].Value);
            DateTime datePaid = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["DATE PAID"].Value);

            // Calculate the difference in days and set the value for "NO. OF DAYS PAID" column
            int noOfDaysPaid = (datePaid - soaReceived).Days;
            e.Value = noOfDaysPaid.ToString();
        }
    }
}


1.确保列名与DataGridView中的列名匹配。
使用此代码,每当DataGridView需要在“NO.如果您在“收到SOA”和“支付日期”列中输入”付款日期“,它将计算“收到SOA”和“支付日期”列中的日期之间的差异,并在“否”列中显示结果。付款日”栏。

相关问题