且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从datagridview中删除隐藏的行。

更新时间:2023-12-05 10:05:16

<asp:TemplateField AccessibleHeaderText="GridDate">
                                            <HeaderTemplate>
                                              GridDate
                                            </HeaderTemplate>
                                            <ItemTemplate>
                                                <%# Eval("LastName")%>
                                            </ItemTemplate>
                                        </asp:TemplateField>
										
										
Use AccessibleHeaderText to find index of this  column then

  Grid.Columns(2).Visible = False


正如你所提到的DataGridView我将提供一个C#Winforms解决方案。



第一点 - 如果你使用日期然后使用 DateTime 变量不是字符串。您没有在 .ToString()上指定任何格式,并且您的startDate和endDate格式不明确,所以只需使用正确的类型。



第二点 - 在将放入DataGridView之前过滤数据总是好得多,例如通过在SQL中使用WHERE子句。



但是,此解决方案假定您已经填充了DataGridView并希望根据列griddate从中删除项目。

As you've mentioned DataGridView I'll offer a C# Winforms solution.

First point - if you are using Dates then use a DateTime variable NOT a string. You haven't specified any formatting on the .ToString() and you have an ambiguous format on your startDate and endDate, so just use the proper type.

Second point - it is always far better to filter the data before you put it into the DataGridView e.g. by using a WHERE clause in SQL.

However, this solution assumes that you have already populated the DataGridView and want to remove items from it based on a column "griddate".
var startDate = new DateTime(2017,2,25,0,0,0);
var endDate = new DateTime(2017, 2, 25, 0, 0, 0);

for (var i = dataGridView1.Rows.Count - 1; i >= 0; i--)
{
        if (dataGridView1.Rows[i].Cells["griddate"].Value == null) continue;
        var griddate = DateTime.Parse(dataGridView1.Rows[i].Cells["griddate"].Value.ToString());
        if (griddate < startDate || griddate > endDate)
                dataGridView1.Rows.RemoveAt(i);
}

请注意,我从行集合的结束开始,然后向后工作。想象一下,我有索引1,2,3,4的行...如果我从头开始并删除第2行然后第4行将不再存在,我将有行索引1,2,3。但是从第1,第2,第3行开始。另一端我会考虑第4行,所以我不在乎它是否重新编号。



如果您在代码中的其他位置看不到行,则删除它们甚至更简单:

Note that I start at the end of the collection of rows and work backwards. Imagine I have rows with indexes 1, 2, 3, 4 ... if I start at the beginning and remove Row 2 then Row 4 will no longer exist, I will have row indexes 1, 2, 3. But by starting at the other end I will have already considered row 4 so I don't care if it gets renumbered.

If you have had rows made invisible elsewhere in the code then removing them is even simpler :

for (var i = dataGridView1.Rows.Count - 1; i >= 0; i--)
{
    if (!dataGridView1.Rows[i].Visible)
        dataGridView1.Rows.RemoveAt(i);
}


dataGridView1.CurrentCell = null;

dataGridView1.Rows[row].Visible = false;