472,777 Members | 2,501 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,777 software developers and data experts.

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 5042
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.
.

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.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 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
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
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...
2
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...
2
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...
3
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...
10
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...
1
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:...
1
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
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
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.