Graham Warrender
Graham Warrender

Reputation: 365

Dynamic DataGrid Headers

I've a problem where i need to get the total number of columns, which defines the total columns. Currently i have a function which dictates the header text on the DataGrid.columns.

public static string ColumnHeader1 = Properties.Settings.Default.ColumnHeader1;

public void dataGridHeaders()
    {
        dataGrid.Columns[0].Header = ColumnHeader1;
        dataGrid.Columns[1].Header = ColumnHeader2;
        dataGrid.Columns[2].Header = ColumnHeader3;
        dataGrid.Columns[3].Header = ColumnHeader4;
        dataGrid.Columns[4].Header = ColumnHeader5;
        dataGrid.Columns[5].Header = ColumnHeader6;
        dataGrid.Columns[6].Header = ColumnHeader7;
        dataGrid.Columns[7].Header = ColumnHeader8;
     }

the string vars being read in from an xml settings file. What i'm looking to do is depending on how many strings in the xml file depicts how many columns there will be at runtime. Or adding an int var say..

public static int totalNumberOfColumns = 8; 

and then iterating through a loop adding the columns.

are any of these ways possible?

Upvotes: 0

Views: 1836

Answers (2)

Jsinh
Jsinh

Reputation: 2579

            var xmlSample = @"<DataGridColumnsHeader>
                            <ColumnHeaderText>Name</ColumnHeaderText>
                            <ColumnHeaderText>Country</ColumnHeaderText>
                            <ColumnHeaderText>Phone</ColumnHeaderText>
                          </DataGridColumns>";

        var counter = 0;
        var elementCount = XDocument.Load(new System.IO.StringReader(xmlSample)).XPathSelectElements("//ColumnHeaderText").Count();
        foreach (var element in XDocument.Load(new System.IO.StringReader(xmlSample)).XPathSelectElements("//ColumnHeaderText"))
        {
            dataGrid.Columns[counter].Header = element.Value;
            counter++;
        }

Hope this helps!

Upvotes: 0

MoonKnight
MoonKnight

Reputation: 23831

Get your column header from the XML file into a string list

List<string> columnHeaderList = new List<string>();
foreach (string header in XmlColumnList)
    columnHeaderList.Add(header);

where XmlColumnList is some array that is holding the values. Now add the following method which will add all the avalible column headers, as rwequired.

private void DataGridHeaders(List<string> headerList)
{
    for (int i = 0; i < headerList.Count; i++)
        dataGrid.Columns[i].Header = headerList[i];
}

I hope this helps.

Upvotes: 1

Related Questions