我正在尝试在我的C#windows应用程序中更改DataGridView
中的某些列值,但是当我尝试分配新值时,会出现一个弹出错误窗口,其中显示:
DataGridView默认错误对话
DataGridView中发生以下异常:...
以下是显示此弹出窗口的屏幕截图,该窗口甚至在try块内显示!
这就是我这样做的方式,首先填充gridview,然后我尝试更改一些列值,即数字,以显示一千个分隔的数值。例如,而不是780000,我得到780,000!
private static string Test(string number)
{
try
{
gridview.DataSource = DBAPI.ExecuteSqlFunction(function, new string[] { CurrentSourceID });
//format price
foreach (DataGridViewRow row in gridview.Rows)
{
row.Cells[2].Value = GetFormattedNumber(row.Cells[2].Value.ToString().Replace(",",""));
}
}
catch (Exception ex)
{
SaveAndShowLog(ex);
}
}
public static string GetFormattedNumber(string number)
{
try
{
return string.Format("{0:N0}", Int64.Parse(number));
}
catch (Exception ex)
{
SaveAndShowLog(ex);
return number;
}
}
答案 0 :(得分:1)
隐藏处理DataGridView.DataError
事件所需的错误消息。
请参阅链接中的示例。
您可以使用DataGridViewCellFormatting
事件来格式化值,并且不要尝试使用字符串值直接替换该值,因为它无论如何都会引发错误。
private static string Test(string number)
{
try
{
gridview.DataSource = DBAPI.ExecuteSqlFunction(function, new string[] { CurrentSourceID });
gridview.CellFormatting += gridView_CellFormatting;
}
catch (Exception ex)
{
SaveAndShowLog(ex);
}
}
public static string GetFormattedNumber(string number)
{
try
{
return string.Format("{0:N0}", Int64.Parse(number));
}
catch (Exception ex)
{
SaveAndShowLog(ex);
return number;
}
}
private static void gridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 2)
{
object val = gridview.Rows[e.RowIndex].Cells[2].Value;
if ((val != null) && !object.ReferenceEquals(val, DBNull.Value))
{
e.Value = GetFormattedNumber(val.ToString().Replace(",", ""));
e.FormattingApplied = true;
}
}
}