gpt4 book ai didi

c# - 无法更改 C# 中的 gridview 单元格,获取数据 GridView 默认错误对话框

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:17 28 4
gpt4 key购买 nike

我试图在我的 C# Windows 应用程序中更改 DataGridView 中的某些列值,但是当我尝试分配新值时,我会弹出一个错误窗口,其中显示:

DataGridView default Error Dialog

the following exception occurred in the DataGridView :...

这是显示此弹出窗口的屏幕截图,它甚至在 try block 内显示! enter image description here
这就是我这样做的方式,首先填充 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;
}
}

最佳答案

要隐藏错误消息,您需要处理 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;
}

}
}

关于c# - 无法更改 C# 中的 gridview 单元格,获取数据 GridView 默认错误对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18916039/

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