代码之家  ›  专栏  ›  技术社区  ›  Hossein

无法更改C#中的网格视图单元格,获取数据网格视图默认错误对话框

  •  2
  • Hossein  · 技术社区  · 13 年前

    我正在尝试更改 DataGridView 在我的C#窗口应用程序中,但当我尝试分配新值时,我会弹出一个错误窗口,上面写着:

    DataGridView默认错误对话框

    DataGridView中出现以下异常:。。。

    这是显示这个弹出窗口的屏幕截图,即使在尝试块内也会显示! enter image description here
    我就是这样做的,首先填充网格视图,然后我尝试更改一些列值,这些列值是数字,用一千个分隔的数值显示。例如,我得到的不是78万,而是78万!

    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;
            }
        }
    
    1 回复  |  直到 13 年前
        1
  •  1
  •   Chris    13 年前

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