【问题标题】:Specified cast is not valid error in Datagridview c#Datagridview c#中的指定转换无效错误
【发布时间】:2015-04-19 21:20:50
【问题描述】:

这是我以前从未遇到过的非常奇怪的错误。我在我的 datagridview 中添加了一个复选框,如下所示:

DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
datagrid.Columns.Insert(0, checkBoxColumn);

我得到了错误

指定的演员表无效

它在数据网格的单元格格式中突出显示了这一点:

for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
{
    if ((int)datagrid.Rows[e.RowIndex].Cells[7].Value <= 5)
    {
        this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }

这会检查单元格 7 中的值是否低于或等于 5,如果是,则将其更改为红色。我尝试将单元格更改为 8,因为我认为它已经移动,因为我在 0 处添加了一个新列,但是它不起作用。

【问题讨论】:

    标签: c# winforms checkbox datagridview


    【解决方案1】:

    试试这个

    for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
    {
        if (Convert.ToInt32(datagrid.Rows[e.RowIndex].Cells[7].Value) <= 5)
        {
    
        }
    

    【讨论】:

    • 是的,但一定要使用 ToInt32()。 Int16 用于特殊场合。
    • 我收到了这个错误Input string was not in a correct format.
    • 你能试试看这给了什么吗:datagrid.Rows[e.RowIndex].Cells[7].Value.ToString() 给了datagrid.Rows[e.RowIndex].Cells[7].Value 或添加一个手表,看看它有什么价值?
    • 对了,你什么时候调用单元格格式化方法?你能把整个代码贴出来吗?
    • 好的,你什么时候添加CheckBox?格式化之前还是之后?
    【解决方案2】:

    尝试使用int.TryParse,它只会在可以成功解析为int 的情况下解析单元格的值。像这样:

    int temp;
    
    for (int i = 0; i <= this.datagrid.Rows.Count - 1; i++)
    {        
        if (int.TryParse(datagrid.Rows[e.RowIndex].Cells[7].Value.ToString(), out temp) == true) 
        {
             if (temp <= 5)
             {
                 this.datagrid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
             }
        }
    

    至少这将停止抛出异常,您可以确定您的单元格格式是否正常工作。我猜您的数据集中有一行在第 7 列和/或第 8 列中有错误值或空值。如果您在位置 0 处添加了这个新的复选框列,那么您现在需要引用 .Cells[8]

    引用列的更好方法是通过名称。然后,如果您将来添加或删除列,则不会在整个代码中弄乱其余的列索引引用。如果你得到上述工作,试试这个:

    if (int.TryParse(datagrid.Rows[e.RowIndex].Cells["yourColumnName"].Value, out temp) == true) 
    

    为了使用此方法,您必须在创建和添加列时指定.Name 列。

    【讨论】:

    • 您好,我已经尝试过您的解决方案,但出现以下错误:The best overloaded method match for 'int.TryParse(string, out int)' has some invalid argumentsArgument 1: cannot convert from 'object' to 'string'
    • 见我上面的编辑。您需要 .ToString() 单元格的值。
    • 是的!谢谢!这样可行!你能告诉我为什么当我添加复选框时它开始给我错误,而没有复选框我的旧代码可以正常工作吗?
    • 在不知道列类型/控件以及网格中的数据类型的情况下很难知道。检查您的数据是否从空值中清除,因为 int.TryParse() 只是跳过它无法解析的任何单元格和行。使用上面的代码,只需数据集中的一条记录即可导致您遇到异常。并关注索引 7 和 8 处的列,因为它们是您现在引用的两列。
    猜你喜欢
    • 2018-02-08
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多