我试图通过检查用户在我的DataGridViewCell中输入的大小是否超过允许的最大值来保护用户免受错误消息的影响。
我做的是:
private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        string selected = (dataGridView3[e.RowIndex, 1] as DataGridViewTextBoxCell).FormattedValue.ToString();
        if (selected.Length > 50)
        {
            dataGridView3[e.RowIndex, 1].Value = selected.Take(50).ToString();
        }
    }
}选中的是我的文本,但我在更新时收到错误信息:无法将字符串转换为int32...如果我使用=0,那就没有意义了。这是怎么回事?
当我更新长度大于50的文本框时出错,它说我的值不是整数。但它必须是一个字符串。我刚从同一个单元格读取了一个字符串。
发布于 2011-05-03 19:12:23
您将行和列放错了
dataGridView3[e.RowIndex, 1]首先是列,然后是行:
dataGridView3[1, e.RowIndex]另外,你一定要在DataGridViewTextBoxCell上选角吗?它对我来说很有效:
string selected = dataGridView3[1, e.RowIndex].FormattedValue.ToString();我的建议是:为什么要在CellEndEdit中使用它,而不是在CellValidating事件中?然后,您可以简化为:
e.FormattedValue.ToString()编辑单元格验证比EndEdit更频繁地触发:即使在单元格选择更改时也是如此。如果对你来说不好,那就像以前一样使用CellEndEdit。如前所述,确保数据源包含字符串,而不是整数。顺便说一句:在我的VS中没有Take()函数,我将其替换为Substring(),尝试如下所示:
private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        string selected = dataGridView3[1, e.RowIndex].FormattedValue.ToString();
        if (selected.Length > 50)
        {
            dataGridView1[3, e.RowIndex].Value = selected.Substring(0, 50);
        }
    }
}发布于 2011-05-03 18:56:18
您必须将字符串转换为正确的Integer值。您正在尝试使用字符串设置Integer值,但它无法执行转换。
https://stackoverflow.com/questions/5868360
复制相似问题