This code takes an XML file with a schema and lets you
select the XML file and then shows the Tables with a Tab
page for the Data and one for the Table layout. This will
give you an idea.
I have the Book ADO.Ndet by Davia Sceppa (microsoft press)
and it has helped me a lot in this.
There is also a routine in here to automatically set the
column width that was copied from the codeguru site
referenced in the comments in the program.
Have fun!
//================================================== ==
//XMLDataGrid by Mike in Paradise,NL
//
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Project1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private string dataBaseName;
private string dataBasePath;
private DataSet theDataSet;
private DataTable columnsTable;
private DataTable selectedTable;
private ArrayList tableList = new ArrayList();
private System.Windows.Forms.ComboBox tableBox;
private System.Windows.Forms.Button changeDataSourceButton;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.DataGrid dataBaseDataGrid;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Windows.Forms.Button saveButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after
InitializeComponent call
//
dataBasePath="../../Data/";
dataBaseName=dataBasePath+"Data.xml";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableBox = new System.Windows.Forms.ComboBox();
this.changeDataSourceButton = new
System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.dataBaseDataGrid = new System.Windows.Forms.DataGrid
();
this.saveButton = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)
(this.dataGrid1)).BeginInit();
this.tabPage2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)
(this.dataBaseDataGrid)).BeginInit();
this.SuspendLayout();
//
// tableBox
//
this.tableBox.ItemHeight = 13;
this.tableBox.Location = new System.Drawing.Point(176, 16);
this.tableBox.Name = "tableBox";
this.tableBox.Size = new System.Drawing.Size(192, 21);
this.tableBox.TabIndex = 12;
this.tableBox.SelectedIndexChanged += new
System.EventHandler(this.tableBox_SelectedIndexCha nged);
//
// changeDataSourceButton
//
this.changeDataSourceButton.Location = new
System.Drawing.Point(24, 16);
this.changeDataSourceButton.Name
= "changeDataSourceButton";
this.changeDataSourceButton.Size = new System.Drawing.Size
(128, 23);
this.changeDataSourceButton.TabIndex = 14;
this.changeDataSourceButton.Text = "Load Data Source";
this.changeDataSourceButton.Click += new
System.EventHandler(this.changeDataSourceButton_Cl ick);
//
// panel1
//
this.panel1.Controls.Add(this.saveButton);
this.panel1.Controls.Add(this.tableBox);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(736, 48);
this.panel1.TabIndex = 15;
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock =
System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0,
48);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(736, 165);
this.tabControl1.TabIndex = 17;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.dataGrid1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(728, 139);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Data";
//
// dataGrid1
//
this.dataGrid1.CaptionVisible = false;
this.dataGrid1.DataMember = "";
this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid1.HeaderForeColor =
System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(0, 0);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(728, 139);
this.dataGrid1.TabIndex = 1;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.dataBaseDataGrid);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(728, 131);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Schema";
//
// dataBaseDataGrid
//
this.dataBaseDataGrid.DataMember = "";
this.dataBaseDataGrid.Dock =
System.Windows.Forms.DockStyle.Fill;
this.dataBaseDataGrid.HeaderForeColor =
System.Drawing.SystemColors.ControlText;
this.dataBaseDataGrid.Location = new System.Drawing.Point
(0, 0);
this.dataBaseDataGrid.Name = "dataBaseDataGrid";
this.dataBaseDataGrid.Size = new System.Drawing.Size(728,
131);
this.dataBaseDataGrid.TabIndex = 17;
//
// saveButton
//
this.saveButton.Location = new System.Drawing.Point(408,
16);
this.saveButton.Name = "saveButton";
this.saveButton.Size = new System.Drawing.Size(144, 23);
this.saveButton.TabIndex = 13;
this.saveButton.Text = "Save Changes";
this.saveButton.Click += new System.EventHandler
(this.saveButton_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(736, 213);
this.Controls.Add(this.changeDataSourceButton);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.panel1.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)
(this.dataGrid1)).EndInit();
this.tabPage2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)
(this.dataBaseDataGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region Main()
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
#endregion
private void changeDataSourceButton_Click(object sender,
System.EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.FileName=dataBaseName;
openFileDialog.AddExtension=true;
openFileDialog.ValidateNames=true;
openFileDialog.DefaultExt="xml";
openFileDialog.CheckFileExists=false;
openFileDialog.InitialDirectory=dataBasePath;
openFileDialog.Filter= "XML files (*.xml)|*.xml|All files
(*.*)|*.*";
openFileDialog.RestoreDirectory=true;
if(openFileDialog.ShowDialog()== DialogResult.OK)
{
dataBaseName=openFileDialog.FileName;
dataBasePath=openFileDialog.InitialDirectory;
LoadDataBase(dataBaseName);
}
}
private void tableBox_SelectedIndexChanged(object sender,
System.EventArgs e)
{
try
{
selectedTable=theDataSet.Tables
[tableBox.SelectedItem.ToString()];
SetupDataGrid();
LoadDataBaseDataGrid();
}
catch
{
MessageBox.Show("Error Please Select a table from the
List");
}
}
#region LoadDataBase()
private bool LoadDataBase(string dataBaseName)
{
//todo load from user preference directory
theDataSet = new DataSet();
try
{
theDataSet.ReadXml(@dataBaseName,XmlReadMode.ReadS chema);
//Populate the tables List
LoadTableList();
}
catch
{
MessageBox.Show("Unable to find your data in"
+"\n DataBase: "+dataBaseName);
LoadTableList();
return false;
}
return true;
}
#endregion LoadDataBase()
#region LoadTableList()
private void LoadTableList()
{
//Populate the tables List
tableList = new ArrayList(theDataSet.Tables);
//Load into the TableBox
tableBox.DataSource=tableList;
if (tableList.Count>0) tableBox.SelectedItem=tableList[0];
else tableBox.SelectedItem = null;
}
#endregion LoadTableList()
#region LoadDataBaseDataGrid()
private void LoadDataBaseDataGrid()
{
//First Create a columns Table made up of Column
Characteristics
//of the selected Table
columnsTable = new DataTable("Columns");
// Add columns to Table
DataColumn columnID = columnsTable.Columns.Add("ColumnID",
typeof(String));
columnID.AllowDBNull = false;
columnID.Unique = true;
columnsTable.Columns.Add("Unique", typeof(System.Boolean));
columnsTable.Columns["Unique"].DefaultValue = false;
columnsTable.Columns.Add("Type", typeof(System.String));
columnsTable.Columns.Add("Control", typeof(System.String));
columnsTable.Columns.Add("Size", typeof(System.Int32));
columnsTable.Columns.Add("Heading", typeof(System.String));
columnsTable.Columns.Add("Format", typeof(System.String));
//Now for each column in the selected Table add a row to
our columns table
//that shows the selected Characteristics
DataRow columnsTableRow;
int i=0;
while( i <= selectedTable.Columns.Count-1 )
{
columnsTableRow = columnsTable.NewRow();
columnsTableRow["ColumnID"] = selectedTable.Columns
[i].ColumnName;
columnsTableRow["Unique"] = selectedTable.Columns
[i].Unique;
columnsTableRow["Type"] = selectedTable.Columns
[i].DataType.ToString();
columnsTableRow["Size"] = selectedTable.Columns
[i].MaxLength;
columnsTableRow["Heading"]= selectedTable.Columns
[i].Caption;
columnsTable.Rows.Add(columnsTableRow);
i++;
}
//Now use the columnsTable as the source for this dataGrid
dataBaseDataGrid.DataSource=columnsTable;
//Create a Grid Style for this grid
DataGridTableStyle dataGridTableStyle = new
DataGridTableStyle();
dataGridTableStyle.MappingName = columnsTable.TableName;
//
// Now Create all the columns and validation tables for
the Grid Style
//
//Create Grid Style for Column 1 - Colunn Name
DataGridTextBoxColumn gridColumn1 = new
DataGridTextBoxColumn();
gridColumn1.MappingName="ColumnID";
gridColumn1.HeaderText="Column Name";
dataGridTableStyle.GridColumnStyles.Add(gridColumn 1);
//Create Grid Style for Column 2 - Unique
DataGridBoolColumn gridColumn2 = new DataGridBoolColumn();
gridColumn2.MappingName="Unique";
gridColumn2.HeaderText="Unique";
dataGridTableStyle.GridColumnStyles.Add(gridColumn 2);
//Create Grid Style for Column 3 - Unique
DataGridBoolColumn gridColumn3 = new DataGridBoolColumn();
gridColumn3.MappingName="Type";
gridColumn3.HeaderText="Type";
dataGridTableStyle.GridColumnStyles.Add(gridColumn 3);
//Create Grid Style for Column 4 - Size
DataGridTextBoxColumn gridColumn4 = new
DataGridTextBoxColumn();
gridColumn4.MappingName="Size";
gridColumn4.HeaderText="Size";
dataGridTableStyle.GridColumnStyles.Add(gridColumn 4);
//Create Grid Style for Column 5 - Headings
DataGridTextBoxColumn gridColumn5 = new
DataGridTextBoxColumn();
gridColumn5.MappingName="Heading";
gridColumn5.HeaderText="Heading";
dataGridTableStyle.GridColumnStyles.Add(gridColumn 5);
//Clean out any old DataGridTable Stylyes
dataGridTableStyle.GridLineStyle = DataGridLineStyle.Solid;
dataGridTableStyle.ColumnHeadersVisible=true;
dataBaseDataGrid.TableStyles.Clear();
dataBaseDataGrid.TableStyles.Add(dataGridTableStyl e);
}
#endregion LoadDataBaseDataGrid()
#region SetupDataGrid()
private void SetupDataGrid()
{
dataGrid1.DataSource=selectedTable;
// currencyManager = (CurrencyManager)
dataGrid1.BindingContext[selectedTable];
//Scan through all the rows to set the column sizes
int nRowsToScan = -1;
SizeColumnsToContent(dataGrid1, nRowsToScan); //Set column
Widths
}
#endregion
#region SizeColumnsToContent()
/// <summary>
/// Auto Sizes Grid Control Columns
/// </summary>
/// <param name="dataGrid"></param>
/// <param name="nRowsToScan"></param>
/// <remarks>
/// This routine was taken from the following website
///
http://www.codeguru.com/cs_controls/...nsToContent.ht
ml
///
/// </remarks>
public void SizeColumnsToContent(DataGrid dataGrid,
int nRowsToScan)
{
// Create graphics object for measuring widths.
Graphics Graphics = dataGrid.CreateGraphics();
// Define new table style.
DataGridTableStyle tableStyle = new DataGridTableStyle();
try
{
DataTable dataTable = (DataTable)dataGrid.DataSource;
if (-1 == nRowsToScan)
{
nRowsToScan = dataTable.Rows.Count;
}
else
{
// Can only scan rows if they exist.
nRowsToScan = System.Math.Min(nRowsToScan,
dataTable.Rows.Count);
}
// Clear any existing table styles.
dataGrid.TableStyles.Clear();
// Use mapping name that is defined in the data source.
tableStyle.MappingName = dataTable.TableName;
// Now create the column styles within the table style.
DataGridTextBoxColumn columnStyle;
int iWidth;
for (int iCurrCol = 0;
iCurrCol < dataTable.Columns.Count; iCurrCol++)
{
DataColumn dataColumn = dataTable.Columns[iCurrCol];
// string lookup = dataColumn.ColumnName.ToString();
// int fieldIndex = fieldsBox.Items.IndexOf(lookup);
{
//
columnStyle = new DataGridTextBoxColumn();
columnStyle.TextBox.Enabled = true;
columnStyle.HeaderText = dataColumn.ColumnName;
columnStyle.MappingName = dataColumn.ColumnName;
// Set width to header text width.
iWidth = (int)(Graphics.MeasureString
(columnStyle.HeaderText,
dataGrid.Font).Width);
// Change width, if data width is
// wider than header text width.
// Check the width of the data in the first X rows.
DataRow dataRow;
for (int iRow = 0; iRow < nRowsToScan; iRow++)
{
dataRow = dataTable.Rows[iRow];
if (null != dataRow[dataColumn.ColumnName])
{
int iColWidth = (int)(Graphics.MeasureString
(dataRow.ItemArray[iCurrCol].ToString(),
dataGrid.Font).Width);
iWidth = (int)System.Math.Max(iWidth, iColWidth);
}
}
columnStyle.Width = iWidth + 4;
columnStyle.NullText = ""; //mjb set nulls to not display
// Add the new column style to the table style.
tableStyle.GridColumnStyles.Add(columnStyle);
}
}
// Add the new table style to the data grid.
dataGrid.TableStyles.Add(tableStyle);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
Graphics.Dispose();
}
}
#endregion SizeColumnsToContent()
private void saveButton_Click(object sender,
System.EventArgs e)
{
theDataSet.WriteXml
(@dataBaseName,XmlWriteMode.WriteSchema);
}
}
}
-----Original Message-----
Hi,
How do I associate or map a specific column in a
datatable to a particularelement present in an xml document - to read into a
datatable as well aswrite from the datatable to the xml element?
Also, how can I associate all the attributes and their
values of aparticular element to the Name & Value columns of a
datatable - to readinto a datatable as well as write from the datatable to
the xml element?
Any help will be greatly appreciated.
Thanks.
.