gpt4 book ai didi

c# - 使用空日期时间对 DataGridView 进行排序

转载 作者:行者123 更新时间:2023-11-30 15:30:17 26 4
gpt4 key购买 nike

我有一个带有一列 DateTime 值的 datagridview,其中一些为空。在我尝试按该列排序之前没有问题。我已经实现了此处的 SortCompare 代码

DataGridView sorting with nulls in DateTime column

但调试器仍然抛出异常并指向我的 Application.Run(new MainForm());线,说

Object must be of type DateTime.

我的 SortCompare 事件处理程序中有一个 try-catch,我能够成功地单步执行所有代码。只有当事件处理程序返回时才会抛出异常。

如何防止这种异常?

代码:

在 Visual Studio 中打开一个新的 c# windows 窗体项目,并在窗体上添加一个带有 Full 停靠样式的数据 GridView 。在 Form1.cs 中,将 public Form1() 方法替换为以下代码:

public Form1()
{
InitializeComponent();

//Create datatable and add a datetime column
DataTable dTable = new DataTable();
DataColumn dColumn = new DataColumn("DateTimes", typeof(DateTime));
dTable.Columns.Add(dColumn);

//Add rows
dTable.Rows.Add(DateTime.Now);
dTable.Rows.Add(DBNull.Value);

//Create a datagridview column and add it to the datagridview
DataGridViewTextBoxColumn dgvColumn = new DataGridViewTextBoxColumn();
dgvColumn.Name = dColumn.ColumnName;
dgvColumn.ValueType = dColumn.DataType;
this.dataGridView1.Columns.Add(dgvColumn);


//Add rows to the datagridview based on datatable data.
foreach (DataRow dRow in dTable.Rows)
{
DataGridViewRow dgvRow = new DataGridViewRow();
dgvRow.CreateCells(this.dataGridView1);
dgvRow.SetValues(dRow.ItemArray);
this.dataGridView1.Rows.Add(dgvRow);
}

//Hook up sortcompare event handler
this.dataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(dataGridView1_SortCompare);

//Style datagridview
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
try
{
if (DBNull.Value.Equals(e.CellValue1) || DBNull.Value.Equals(e.CellValue2))
{
if (DBNull.Value.Equals(e.CellValue1) || e.CellValue1.Equals(null))
{
e.SortResult = 1;
}
else if (DBNull.Value.Equals(e.CellValue2) || e.CellValue2.Equals(null))
{
e.SortResult = -1;
}
}
else
{
e.SortResult = (e.CellValue1 as IComparable).CompareTo(e.CellValue2 as IComparable);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

然后运行程序,尝试对列进行排序抛出异常。

最佳答案

你错过了 e.Handled = true;将其设置为 true 将解决您的问题。

 private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
try
{
if (DBNull.Value.Equals(e.CellValue1) || DBNull.Value.Equals(e.CellValue2))
{
if (DBNull.Value.Equals(e.CellValue1) || e.CellValue1.Equals(null))
{
e.SortResult = 1;
}
else if (DBNull.Value.Equals(e.CellValue2) || e.CellValue2.Equals(null))
{
e.SortResult = -1;
}
}
else
{
e.SortResult = (e.CellValue1 as IComparable).CompareTo(e.CellValue2 as IComparable);
}
e.Handled = true
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

关于c# - 使用空日期时间对 DataGridView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com