ILovephp123 ILovephp123 - 3 months ago 21
C# Question

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?

Answer

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);
    }
}