473,545 Members | 1,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mapping a datatable column to an xml element

Hi,
How do I associate or map a specific column in a datatable to a particular
element present in an xml document - to read into a datatable as well as
write from the datatable to the xml element?
Also, how can I associate all the attributes and their values of a
particular element to the Name & Value columns of a datatable - to read
into a datatable as well as write from the datatable to the xml element?

Any help will be greatly appreciated.

Thanks.
Nov 11 '05 #1
2 5122
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.
.

Nov 11 '05 #2
Thanks.

"Mike in Paradise NL" <ka************ *@hotmail.cm> wrote in message
news:08******** *************** *****@phx.gbl.. .
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 particular
element present in an xml document - to read into a

datatable as well as
write from the datatable to the xml element?
Also, how can I associate all the attributes and their

values of a
particular element to the Name & Value columns of a

datatable - to read
into a datatable as well as write from the datatable to

the xml element?

Any help will be greatly appreciated.

Thanks.
.

Nov 11 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2031
by: mike | last post by:
regards: Where to find tag mapping-table of HTML translated to XHTML1.0 Any positive suggestion is welcome. thank you May goodness be with you all
0
1118
by: Tim Nelson | last post by:
I just created an XSD file to map my XML data I want to load into the a dataset. Everything is rosy since all of my XML is basically elements with attributes. I can read the schema and bring in a XML document and load it into a grid and it recognizes the child tables (elements) perfectly. Only problem is I have two elements that don't have...
2
3109
by: Scott | last post by:
Hi all. A few days ago i ask this question and got a good quick response. I tried out what they said and it worked. However I have now come to try the same thing in another program and it does not seem to be working.
2
7959
by: MattB | last post by:
I know I can use dataviews and more looping to do this, but I'm wondering if there's a more elegant or more concise way to do this. I've got two DataTables with a column called guest_no. I'd love to be able to use something like the .IndexOf method of arrays and bound controls. Somehting like: Dim r as DataRow For Each r in...
3
3180
by: Jon | last post by:
I'm learning about datatables. When using the example provided by MS in the ..NET Framework Class Library for DATATABLE (see below) I get an error on line 3 that says "Type expected". Is something missing from the code? Thanks - Jon Private Sub MakeParentTable() ' Create a new DataTable. Dim myDataTable As Datatable = New...
10
4933
by: JohnR | last post by:
I have a datatable as the datasource to a datagrid. The datagrid has a datagridtablestyle defined. I use the datagridtablestyle to change the order of the columns (so they can be different than the column order of the datatable). I also allow the user to click on a column header to sort the datagrid by that column. I need to identify...
1
1708
by: none | last post by:
Hi, I'm trying to establish table mappings, and I've hit a snag. At the point to where I try to fill the schema (DB_adapter.FillSchema), I get an exception, and the message is as follows: :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Invalid column name 'Unique_ref'. Invalid column name 'ID_string'. Invalid column...
1
1314
by: luthriaajay | last post by:
I am creating elements and attributes in my XSL. I need to first map the element created with the table name? Is this possible in XSL? I am using Java. For example :
2
3411
by: devnew | last post by:
hi i am looking for some info about mapping btw values in an array and corresponding columns of a matrix i have an numpy array= and a numpy matrix object= matrix((, , , ))
0
7479
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7411
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7669
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7926
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4962
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3468
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.