简体   繁体   中英

Check if column exists in DataGridView

for (int i = 0; i < completeInfoMatches.Count; i++) {
    if (!(databaseGridView.Columns.Contains(e.Node.Parent.Text))) {
        Console.WriteLine(e.Node.Parent.Text);
        databaseGridView.Columns.Add("column" + i, e.Node.Parent.Text);
    }
}

If the column has the name already, I do not want it to be added.

My code seems like it would work, but for some reason it doesn't?

It seems that your e.Node.Parent.Text string refers to the HeaderText of the column not to the Name property. If this is the case then the code to find if an HeaderText exists with the same value of your e.Node.Parent.Text is the following

for (int i = 0; i < completeInfoMatches.Count; i++) 
{
    if (!(databaseGridView.Columns
              .Cast<DataGridViewColumn>()
              .Any(x => x.HeaderText == e.Node.Parent.Text))) 
    {
        Console.WriteLine(e.Node.Parent.Text);
        databaseGridView.Columns.Add("column" + i, e.Node.Parent.Text);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM