c#讀取xml檔案到datagridview執行個體

來源:互聯網
上載者:User

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace QueryXMLByLINQ
{
public partial class Frm_Main : Form
{
public Frm_Main()
{
InitializeComponent();
}

static string strPath = "Employee.xml";
static string strID = "";

//表單載入時載入XML檔案
private void Form1_Load(object sender, EventArgs e)
{
getXmlInfo();
}

//顯示選中XML節點的詳細資料
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
strID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();//記錄選擇的職工編號
XElement xe = XElement.Load(strPath);//載入XML檔案
//使用LINT從XML檔案中查詢資訊
IEnumerable<XElement> elements = from PInfo in xe.Elements("People")
where PInfo.Attribute("ID").Value == strID
select PInfo;
foreach (XElement element in elements)//遍曆查詢結果
{
textBox11.Text = element.Element("Name").Value;//顯示職工姓名
comboBox1.SelectedItem = element.Element("Sex").Value;//顯示職工性別
textBox12.Text = element.Element("Salary").Value;//顯示職工薪水
}
}

#region 將XML檔案內容綁定到DataGridView控制項
/// <summary>
/// 將XML檔案內容綁定到DataGridView控制項
/// </summary>
private void getXmlInfo()
{
DataSet myds = new DataSet();
myds.ReadXml(strPath);
dataGridView1.DataSource = myds.Tables[0];
}
#endregion
}
}

複製代碼 代碼如下:<?xml version="1.0" encoding="UTF-8"?>
-<Peoples> -<People ID="001"> <Name>小王</Name> <Sex>男</Sex> <Salary>1500</Salary> </People> -<People ID="002"> <Name>小呂</Name> <Sex>男</Sex> <Salary>1500</Salary> </People> -<People ID="003"> <Name>小梁</Name> <Sex>男</Sex> <Salary>1500</Salary> </People> </Peoples>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.