Bind Config section to DataTable using c#

Posted by srk on Stack Overflow See other posts from Stack Overflow or by srk
Published on 2010-06-08T08:33:05Z Indexed on 2010/06/08 9:42 UTC
Read the original article Hit count: 238

Filed under:

I have the following config section in my app.config file and the code to iterate through config section to retrieve the values. But i want to save the values of config section to a datatable in a proper structure. How ? I want to show all the values in datagridview with appropriate columns.

  <configSections>
    <section name="ServerInfo" type="System.Configuration.IConfigurationSectionHandler" />
  </configSections>

  <ServerInfo>
    <Server id="1">
      <Name>SRUAV1</Name>
      <key> 1 </key>
      <IP>10.1.150.110</IP>
      <Port>7901</Port> 
    </Server>
    <Server id="2">
      <Name>SRUAV2</Name>
      <key> 4 </key>
      <IP>10.1.150.110</IP>
      <Port>7902</Port>
    </Server>
    <Server id="3">
      <Name>SRUAV3</Name>
      <key> 6 </key>
      <IP>10.1.150.110</IP>
      <Port>7904</Port>
    </Server>
  </ServerInfo>

Code :

public void GetServerValues(string strSelectedServer)
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        ConfigurationSection section = config.GetSection("ServerInfo"); 
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(section.SectionInformation.GetRawXml());
        string temp = "";
        XmlNodeList applicationList = xml.DocumentElement.SelectNodes("Server"); 
        for (int i = 0; i < applicationList.Count; i++)
        {
            object objAppId = applicationList[i].Attributes["id"];
            int iAppId = 0;
            if (objAppId != null)
            {
                iAppId = Convert.ToInt32(applicationList[i].Attributes["id"].Value);
            } 
            temp = BuildServerValues(applicationList[i]);
        } 
    }

    public string BuildServerValues(XmlNode applicationNode)
    {
        for (int i = 0; i < applicationNode.ChildNodes.Count; i++)
        {
            if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Name"))
            {
                strServerName = applicationNode.ChildNodes.Item(i).InnerXml.ToString();
            }
            if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("IP"))
            {
                strIP = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); 
            }
            if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Port"))
            {
                strPort = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); 
            }
        }
        return strServerName;
    }

© Stack Overflow or respective owner

Related posts about c#