Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么不从DataGridView中删除DataGridColumn_C#_Winforms_Datagridview - Fatal编程技术网

C# 为什么不从DataGridView中删除DataGridColumn

C# 为什么不从DataGridView中删除DataGridColumn,c#,winforms,datagridview,C#,Winforms,Datagridview,我有自定义的DataGridView控件,在该控件中有RefreshGrid()方法,该方法使用数据源填充DataGridView。现在,我试图在数据源绑定后从DataGridView中删除一些列,但无法删除这些列,这些列没有被删除,而是添加到DataGridView的末尾,当我再次调用RefreshGrid()方法时,这些列将从DataGridView中删除。下面是方法RefreshGrid() 调用RefreshGrid() 请查找错误并向我建议解决方案。您应该只从数据表中检索要在DataG

我有自定义的
DataGridView
控件,在该控件中有
RefreshGrid()
方法,该方法使用数据源填充
DataGridView
。现在,我试图在数据源绑定后从
DataGridView
中删除一些列,但无法删除这些列,这些列没有被删除,而是添加到DataGridView的末尾,当我再次调用
RefreshGrid()
方法时,这些列将从
DataGridView
中删除。下面是方法
RefreshGrid()

调用RefreshGrid()


请查找错误并向我建议解决方案。

您应该只从数据表中检索要在DataGridView中显示的列

var results = _table
    .AsEnumerable()
    .Where("Add your condition")
    .Select("your columns names");

this.DataSource = results;

所以现在您不需要从DataGridView中删除任何列

我找到了这个问题的答案

我需要在Form Load上调用RefreshGrid()方法,而不是在Form构造函数上,在Form Load上调用它之后,我的问题得到了解决。但我不知道它为什么不在表单构造函数上工作


我找到了这个问题的答案

我需要在表单加载而不是表单加载时调用RefreshGrid()方法 构造函数,在窗体日志上调用它之后,我的问题得到了解决。但我 不知道为什么表单构造函数不起作用

我猜您试图访问尚不存在的列。您使用的是
DataGridView.AutoGenerateColumns
功能性,即使设置了
DataSource
属性,
DataGridView
也不会创建列,直到显示网格。这就是为什么它不在表单构造函数中工作,而是在
form\u Load
事件中工作,或者在网格显示之后工作


使用
form\u Load
可能是一种可行的解决方法,但我再次要求您使用专门为处理这种情况而设计的事件。

现在我尝试在数据源绑定后从DataGridView中删除几列???请向我们显示在数据源绑定后删除这些列的代码。代码正常工作,绑定后始终可以删除datagridviewcolumns。@MicrosoftDN
this.columns.remove(colm)
@KingKing是的,这是有效的,但是当我第二次调用
RefreshGrid()
时这是什么:如果(!string.IsNullOrEmpty(“Colm1”))这会删除/过滤掉行而不是列?@KingKing:从linq中的select语句中,我们只会得到我们需要的列。可以移除cond的位置。如果不需要,我忽略了
选择
,但是如果OP希望其数据源为
数据表
,则仍然需要
CopyToDataTable。我想我们必须在这里使用
匿名类型
来选择列,所以不能使用
CopyToDataTable
。@King King:可以,如果后期处理需要数据表。@PankajAgarwal是的,这也行,但我希望数据源中的这些列可以使用DataAdapter在数据库中进行更新
    public Form1()
    {
        InitializeComponent();
        myDataGridView1.RefreshGrid();
    }
var results = _table
    .AsEnumerable()
    .Where("Add your condition")
    .Select("your columns names");

this.DataSource = results;