C# 无法添加列,因为其 CellType 属性为空异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/269365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:54:13  来源:igfitidea点击:

Column cannot be added because its CellType property is null exception

c#datagridview

提问by Niko Gamulin

I have trouble with the following piece of code. When I go through with the debugger I get an exception when it comes to the following line:

我在处理以下代码时遇到问题。当我使用调试器时,遇到以下行时出现异常:

dgvCalls.Columns.Insert(1, msisnnColumn);

I get an exception:

我得到一个例外:

Column cannot be added because its CellType property is null.

无法添加列,因为其 CellType 属性为空。

Oddly, I created the same procedure for some other DataGridViews and it worked fine.

奇怪的是,我为其他一些 DataGridView 创建了相同的过程,并且运行良好。

if (!(dgvCalls.Columns.Contains("DirectionImage")))
                {
                    directionIconColumn = new DataGridViewImageColumn();
                    directionIconColumn.Name = "DirectionImage";
                    directionIconColumn.HeaderText = "";
                    dgvCalls.Columns.Insert(0, directionIconColumn);
                    directionIconColumn.CellTemplate = new DataGridViewImageCell();
                }
                if (!(dgvCalls.Columns.Contains("msisndColumn")))
                {
                    msisnnColumn = new DataGridViewColumn();
                    msisnnColumn.Name = "msisndColumn";
                    msisnnColumn.HeaderText = "Klic";
                    dgvCalls.Columns.Insert(1, msisnnColumn);
                    msisnnColumn.CellTemplate = new DataGridViewTextBoxCell();
                }

Any suggestions?

有什么建议?

采纳答案by BFree

dgvCalls.Columns.Insert(1, msisnnColumn);
msisnnColumn.CellTemplate = new DataGridViewTextBoxCell();

Try flipping those two lines. That might do the trick.

尝试翻转这两行。这可能会奏效。