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.Collecti ons;
using System.Componen tModel;
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 changeDataSourc eButton;
private System.Windows. Forms.Panel panel1;
private System.Windows. Forms.TabContro l tabControl1;
private System.Windows. Forms.TabPage tabPage1;
private System.Windows. Forms.TabPage tabPage2;
private System.Windows. Forms.DataGrid dataBaseDataGri d;
private System.Windows. Forms.DataGrid dataGrid1;
private System.Windows. Forms.Button saveButton;
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();
//
// TODO: Add any constructor code after
InitializeCompo nent call
//
dataBasePath=". ./../Data/";
dataBaseName=da taBasePath+"Dat a.xml";
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Disp ose();
}
}
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 InitializeCompo nent()
{
this.tableBox = new System.Windows. Forms.ComboBox( );
this.changeData SourceButton = new
System.Windows. Forms.Button();
this.panel1 = new System.Windows. Forms.Panel();
this.tabControl 1 = new System.Windows. Forms.TabContro l();
this.tabPage1 = new System.Windows. Forms.TabPage() ;
this.dataGrid1 = new System.Windows. Forms.DataGrid( );
this.tabPage2 = new System.Windows. Forms.TabPage() ;
this.dataBaseDa taGrid = new System.Windows. Forms.DataGrid
();
this.saveButton = new System.Windows. Forms.Button();
this.panel1.Sus pendLayout();
this.tabControl 1.SuspendLayout ();
this.tabPage1.S uspendLayout();
((System.Compon entModel.ISuppo rtInitialize)
(this.dataGrid1 )).BeginInit();
this.tabPage2.S uspendLayout();
((System.Compon entModel.ISuppo rtInitialize)
(this.dataBaseD ataGrid)).Begin Init();
this.SuspendLay out();
//
// tableBox
//
this.tableBox.I temHeight = 13;
this.tableBox.L ocation = new System.Drawing. Point(176, 16);
this.tableBox.N ame = "tableBox";
this.tableBox.S ize = new System.Drawing. Size(192, 21);
this.tableBox.T abIndex = 12;
this.tableBox.S electedIndexCha nged += new
System.EventHan dler(this.table Box_SelectedInd exChanged);
//
// changeDataSourc eButton
//
this.changeData SourceButton.Lo cation = new
System.Drawing. Point(24, 16);
this.changeData SourceButton.Na me
= "changeDataSour ceButton";
this.changeData SourceButton.Si ze = new System.Drawing. Size
(128, 23);
this.changeData SourceButton.Ta bIndex = 14;
this.changeData SourceButton.Te xt = "Load Data Source";
this.changeData SourceButton.Cl ick += new
System.EventHan dler(this.chang eDataSourceButt on_Click);
//
// panel1
//
this.panel1.Con trols.Add(this. saveButton);
this.panel1.Con trols.Add(this. tableBox);
this.panel1.Doc k = System.Windows. Forms.DockStyle .Top;
this.panel1.Loc ation = new System.Drawing. Point(0, 0);
this.panel1.Nam e = "panel1";
this.panel1.Siz e = new System.Drawing. Size(736, 48);
this.panel1.Tab Index = 15;
//
// tabControl1
//
this.tabControl 1.Controls.Add( this.tabPage1);
this.tabControl 1.Controls.Add( this.tabPage2);
this.tabControl 1.Dock =
System.Windows. Forms.DockStyle .Fill;
this.tabControl 1.Location = new System.Drawing. Point(0,
48);
this.tabControl 1.Name = "tabControl 1";
this.tabControl 1.SelectedIndex = 0;
this.tabControl 1.Size = new System.Drawing. Size(736, 165);
this.tabControl 1.TabIndex = 17;
//
// tabPage1
//
this.tabPage1.C ontrols.Add(thi s.dataGrid1);
this.tabPage1.L ocation = new System.Drawing. Point(4, 22);
this.tabPage1.N ame = "tabPage1";
this.tabPage1.S ize = new System.Drawing. Size(728, 139);
this.tabPage1.T abIndex = 0;
this.tabPage1.T ext = "Data";
//
// dataGrid1
//
this.dataGrid1. CaptionVisible = false;
this.dataGrid1. DataMember = "";
this.dataGrid1. Dock = System.Windows. Forms.DockStyle .Fill;
this.dataGrid1. HeaderForeColor =
System.Drawing. SystemColors.Co ntrolText;
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.C ontrols.Add(thi s.dataBaseDataG rid);
this.tabPage2.L ocation = new System.Drawing. Point(4, 22);
this.tabPage2.N ame = "tabPage2";
this.tabPage2.S ize = new System.Drawing. Size(728, 131);
this.tabPage2.T abIndex = 1;
this.tabPage2.T ext = "Schema";
//
// dataBaseDataGri d
//
this.dataBaseDa taGrid.DataMemb er = "";
this.dataBaseDa taGrid.Dock =
System.Windows. Forms.DockStyle .Fill;
this.dataBaseDa taGrid.HeaderFo reColor =
System.Drawing. SystemColors.Co ntrolText;
this.dataBaseDa taGrid.Location = new System.Drawing. Point
(0, 0);
this.dataBaseDa taGrid.Name = "dataBaseDataGr id";
this.dataBaseDa taGrid.Size = new System.Drawing. Size(728,
131);
this.dataBaseDa taGrid.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.EventHan dler
(this.saveButto n_Click);
//
// Form1
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(736, 213);
this.Controls.A dd(this.changeD ataSourceButton );
this.Controls.A dd(this.tabCont rol1);
this.Controls.A dd(this.panel1) ;
this.Name = "Form1";
this.Text = "Form1";
this.panel1.Res umeLayout(false );
this.tabControl 1.ResumeLayout( false);
this.tabPage1.R esumeLayout(fal se);
((System.Compon entModel.ISuppo rtInitialize)
(this.dataGrid1 )).EndInit();
this.tabPage2.R esumeLayout(fal se);
((System.Compon entModel.ISuppo rtInitialize)
(this.dataBaseD ataGrid)).EndIn it();
this.ResumeLayo ut(false);
}
#endregion
#region Main()
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run (new Form1());
}
#endregion
private void changeDataSourc eButton_Click(o bject sender,
System.EventArg s e)
{
OpenFileDialog openFileDialog = new OpenFileDialog( );
openFileDialog. FileName=dataBa seName;
openFileDialog. AddExtension=tr ue;
openFileDialog. ValidateNames=t rue;
openFileDialog. DefaultExt="xml ";
openFileDialog. CheckFileExists =false;
openFileDialog. InitialDirector y=dataBasePath;
openFileDialog. Filter= "XML files (*.xml)|*.xml|A ll files
(*.*)|*.*";
openFileDialog. RestoreDirector y=true;
if(openFileDial og.ShowDialog() == DialogResult.OK )
{
dataBaseName=op enFileDialog.Fi leName;
dataBasePath=op enFileDialog.In itialDirectory;
LoadDataBase(da taBaseName);
}
}
private void tableBox_Select edIndexChanged( object sender,
System.EventArg s e)
{
try
{
selectedTable=t heDataSet.Table s
[tableBox.Select edItem.ToString ()];
SetupDataGrid() ;
LoadDataBaseDat aGrid();
}
catch
{
MessageBox.Show ("Error Please Select a table from the
List");
}
}
#region LoadDataBase()
private bool LoadDataBase(st ring dataBaseName)
{
//todo load from user preference directory
theDataSet = new DataSet();
try
{
theDataSet.Read Xml(@dataBaseNa me,XmlReadMode. ReadSchema);
//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(theDa taSet.Tables);
//Load into the TableBox
tableBox.DataSo urce=tableList;
if (tableList.Coun t>0) tableBox.Select edItem=tableLis t[0];
else tableBox.Select edItem = null;
}
#endregion LoadTableList()
#region LoadDataBaseDat aGrid()
private void LoadDataBaseDat aGrid()
{
//First Create a columns Table made up of Column
Characteristics
//of the selected Table
columnsTable = new DataTable("Colu mns");
// Add columns to Table
DataColumn columnID = columnsTable.Co lumns.Add("Colu mnID",
typeof(String)) ;
columnID.AllowD BNull = false;
columnID.Unique = true;
columnsTable.Co lumns.Add("Uniq ue", typeof(System.B oolean));
columnsTable.Co lumns["Unique"].DefaultValue = false;
columnsTable.Co lumns.Add("Type ", typeof(System.S tring));
columnsTable.Co lumns.Add("Cont rol", typeof(System.S tring));
columnsTable.Co lumns.Add("Size ", typeof(System.I nt32));
columnsTable.Co lumns.Add("Head ing", typeof(System.S tring));
columnsTable.Co lumns.Add("Form at", typeof(System.S tring));
//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.C olumns.Count-1 )
{
columnsTableRow = columnsTable.Ne wRow();
columnsTableRow["ColumnID"] = selectedTable.C olumns
[i].ColumnName;
columnsTableRow["Unique"] = selectedTable.C olumns
[i].Unique;
columnsTableRow["Type"] = selectedTable.C olumns
[i].DataType.ToStr ing();
columnsTableRow["Size"] = selectedTable.C olumns
[i].MaxLength;
columnsTableRow["Heading"]= selectedTable.C olumns
[i].Caption;
columnsTable.Ro ws.Add(columnsT ableRow);
i++;
}
//Now use the columnsTable as the source for this dataGrid
dataBaseDataGri d.DataSource=co lumnsTable;
//Create a Grid Style for this grid
DataGridTableSt yle dataGridTableSt yle = new
DataGridTableSt yle();
dataGridTableSt yle.MappingName = columnsTable.Ta bleName;
//
// Now Create all the columns and validation tables for
the Grid Style
//
//Create Grid Style for Column 1 - Colunn Name
DataGridTextBox Column gridColumn1 = new
DataGridTextBox Column();
gridColumn1.Map pingName="Colum nID";
gridColumn1.Hea derText="Column Name";
dataGridTableSt yle.GridColumnS tyles.Add(gridC olumn1);
//Create Grid Style for Column 2 - Unique
DataGridBoolCol umn gridColumn2 = new DataGridBoolCol umn();
gridColumn2.Map pingName="Uniqu e";
gridColumn2.Hea derText="Unique ";
dataGridTableSt yle.GridColumnS tyles.Add(gridC olumn2);
//Create Grid Style for Column 3 - Unique
DataGridBoolCol umn gridColumn3 = new DataGridBoolCol umn();
gridColumn3.Map pingName="Type" ;
gridColumn3.Hea derText="Type";
dataGridTableSt yle.GridColumnS tyles.Add(gridC olumn3);
//Create Grid Style for Column 4 - Size
DataGridTextBox Column gridColumn4 = new
DataGridTextBox Column();
gridColumn4.Map pingName="Size" ;
gridColumn4.Hea derText="Size";
dataGridTableSt yle.GridColumnS tyles.Add(gridC olumn4);
//Create Grid Style for Column 5 - Headings
DataGridTextBox Column gridColumn5 = new
DataGridTextBox Column();
gridColumn5.Map pingName="Headi ng";
gridColumn5.Hea derText="Headin g";
dataGridTableSt yle.GridColumnS tyles.Add(gridC olumn5);
//Clean out any old DataGridTable Stylyes
dataGridTableSt yle.GridLineSty le = DataGridLineSty le.Solid;
dataGridTableSt yle.ColumnHeade rsVisible=true;
dataBaseDataGri d.TableStyles.C lear();
dataBaseDataGri d.TableStyles.A dd(dataGridTabl eStyle);
}
#endregion LoadDataBaseDat aGrid()
#region SetupDataGrid()
private void SetupDataGrid()
{
dataGrid1.DataS ource=selectedT able;
// currencyManager = (CurrencyManage r)
dataGrid1.Bindi ngContext[selectedTable];
//Scan through all the rows to set the column sizes
int nRowsToScan = -1;
SizeColumnsToCo ntent(dataGrid1 , nRowsToScan); //Set column
Widths
}
#endregion
#region SizeColumnsToCo ntent()
/// <summary>
/// Auto Sizes Grid Control Columns
/// </summary>
/// <param name="dataGrid" ></param>
/// <param name="nRowsToSc an"></param>
/// <remarks>
/// This routine was taken from the following website
///
http://www.codeguru.com/cs_controls/...nsToContent.ht
ml
///
/// </remarks>
public void SizeColumnsToCo ntent(DataGrid dataGrid,
int nRowsToScan)
{
// Create graphics object for measuring widths.
Graphics Graphics = dataGrid.Create Graphics();
// Define new table style.
DataGridTableSt yle tableStyle = new DataGridTableSt yle();
try
{
DataTable dataTable = (DataTable)data Grid.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.TableS tyles.Clear();
// Use mapping name that is defined in the data source.
tableStyle.Mapp ingName = dataTable.Table Name;
// Now create the column styles within the table style.
DataGridTextBox Column columnStyle;
int iWidth;
for (int iCurrCol = 0;
iCurrCol < dataTable.Colum ns.Count; iCurrCol++)
{
DataColumn dataColumn = dataTable.Colum ns[iCurrCol];
// string lookup = dataColumn.Colu mnName.ToString ();
// int fieldIndex = fieldsBox.Items .IndexOf(lookup );
{
//
columnStyle = new DataGridTextBox Column();
columnStyle.Tex tBox.Enabled = true;
columnStyle.Hea derText = dataColumn.Colu mnName;
columnStyle.Map pingName = dataColumn.Colu mnName;
// Set width to header text width.
iWidth = (int)(Graphics. MeasureString
(columnStyle.He aderText,
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.Colu mnName])
{
int iColWidth = (int)(Graphics. MeasureString
(dataRow.ItemAr ray[iCurrCol].ToString(),
dataGrid.Font). Width);
iWidth = (int)System.Mat h.Max(iWidth, iColWidth);
}
}
columnStyle.Wid th = iWidth + 4;
columnStyle.Nul lText = ""; //mjb set nulls to not display
// Add the new column style to the table style.
tableStyle.Grid ColumnStyles.Ad d(columnStyle);
}
}
// Add the new table style to the data grid.
dataGrid.TableS tyles.Add(table Style);
}
catch(Exception e)
{
MessageBox.Show (e.Message);
}
finally
{
Graphics.Dispos e();
}
}
#endregion SizeColumnsToCo ntent()
private void saveButton_Clic k(object sender,
System.EventArg s e)
{
theDataSet.Writ eXml
(@dataBaseName, XmlWriteMode.Wr iteSchema);
}
}
}
-----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.
.