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.


0
anitac (15)
8/12/2003 11:24:05 PM
dotnet.xml 7266 articles. 0 followers. Follow

2 Replies
964 Views

Similar Articles

[PageSpeed] 49

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_SelectedIndexChanged);
//
// 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_Click);
//
// 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.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(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(gridColumn1);

//Create Grid Style for Column 2 - Unique
DataGridBoolColumn gridColumn2 = new DataGridBoolColumn();
gridColumn2.MappingName="Unique";
gridColumn2.HeaderText="Unique";

dataGridTableStyle.GridColumnStyles.Add(gridColumn2);

//Create Grid Style for Column 3 - Unique
DataGridBoolColumn gridColumn3 = new DataGridBoolColumn();
gridColumn3.MappingName="Type";
gridColumn3.HeaderText="Type";

dataGridTableStyle.GridColumnStyles.Add(gridColumn3);


//Create Grid Style for Column 4 - Size
DataGridTextBoxColumn gridColumn4 = new 
DataGridTextBoxColumn();
gridColumn4.MappingName="Size";
gridColumn4.HeaderText="Size";
dataGridTableStyle.GridColumnStyles.Add(gridColumn4);

//Create Grid Style for Column 5 - Headings
DataGridTextBoxColumn gridColumn5 = new 
DataGridTextBoxColumn();
gridColumn5.MappingName="Heading";
gridColumn5.HeaderText="Heading";
dataGridTableStyle.GridColumnStyles.Add(gridColumn5);

//Clean out any old DataGridTable Stylyes
dataGridTableStyle.GridLineStyle = DataGridLineStyle.Solid;
dataGridTableStyle.ColumnHeadersVisible=true;
dataBaseDataGrid.TableStyles.Clear();
dataBaseDataGrid.TableStyles.Add(dataGridTableStyle);
}
#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/SizeColumnsToContent.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.
>
>
>.
>
0
8/14/2003 3:54:48 PM
Thanks.

"Mike in Paradise NL" <kanuk_eh.nospae@hotmail.cm> wrote in message
news:08fb01c3627c$638ba9f0$a001280a@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_SelectedIndexChanged);
> //
> // 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_Click);
> //
> // 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.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(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(gridColumn1);
>
> //Create Grid Style for Column 2 - Unique
> DataGridBoolColumn gridColumn2 = new DataGridBoolColumn();
> gridColumn2.MappingName="Unique";
> gridColumn2.HeaderText="Unique";
>
> dataGridTableStyle.GridColumnStyles.Add(gridColumn2);
>
> //Create Grid Style for Column 3 - Unique
> DataGridBoolColumn gridColumn3 = new DataGridBoolColumn();
> gridColumn3.MappingName="Type";
> gridColumn3.HeaderText="Type";
>
> dataGridTableStyle.GridColumnStyles.Add(gridColumn3);
>
>
> //Create Grid Style for Column 4 - Size
> DataGridTextBoxColumn gridColumn4 = new
> DataGridTextBoxColumn();
> gridColumn4.MappingName="Size";
> gridColumn4.HeaderText="Size";
> dataGridTableStyle.GridColumnStyles.Add(gridColumn4);
>
> //Create Grid Style for Column 5 - Headings
> DataGridTextBoxColumn gridColumn5 = new
> DataGridTextBoxColumn();
> gridColumn5.MappingName="Heading";
> gridColumn5.HeaderText="Heading";
> dataGridTableStyle.GridColumnStyles.Add(gridColumn5);
>
> //Clean out any old DataGridTable Stylyes
> dataGridTableStyle.GridLineStyle = DataGridLineStyle.Solid;
> dataGridTableStyle.ColumnHeadersVisible=true;
> dataBaseDataGrid.TableStyles.Clear();
> dataBaseDataGrid.TableStyles.Add(dataGridTableStyle);
> }
> #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/SizeColumnsToContent.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.
> >
> >
> >.
> >


0
anitac (15)
8/14/2003 9:23:08 PM
Reply:

Similar Artilces:

Vlookup with variable column reference
Help! I am trying to link two workbooks with a vlookup that searches for the last populated columns' entry in a range (see example below). 27/03 28/03 29/03 30/03 31/03 Data 6 4 Is there a way of doing this in a function? In a macro I would use the Range().End(xltoleft) code but I cannot figure out how to do something similar in a worksheet function. I basically want the lookup column to start at day 31 and make its way backwards until it finds a value. Another issue is that the seemingly blank cells contain formula - ie. not empty. Any ideas? Thanks!! Jen 1 ...

variable column names in a report
i have an application where the user can enter self selected column names which then in turn are added to a table... application works fine. however, when it comes to reporting, how do i go about adding those self entered columns in a report? any help would be appreciated Do you actually need this in a report or can the results be pushed to Excel for printing? -- Duane Hookom MS Access MVP Help me support UCP http://www.access.hookom.net/UCP/Default.htm "k2sarah" <k2sarah@discussions.microsoft.com> wrote in message news:C56B6FD1-2F5B-45D5-8760-A61E3CA41495@microsoft.c...

id() node-set function does not work in .NET 1.1 XML Classes
The id() nodeset XPath function does not appear to work when used with XPathDocument and XslTransformation dot net classes. I am trying to make use of IDREFs in XML that link elements to other elements in the document. The code below demonstrates the problem. I SHOULD be getting a line that says "NODES MATCH". Instead I get a "NO NODES MATCH". All the of the W3C stuff I have found says that this should work. Any ideas? robert sutton ==== HERE IS THE OUTPUT This is element Foo! name is bar ID is idfoo --------------------------- Found reference element, it refers to idfo...

Hide Cell Content if no data in previous columns
I've made this work many years ago but now can't remember how. I have a job invoice to where the rate is 40.00/hour. This 40.00 is used in calculation to determine the total amount of pay owed. (20 hours worked * 40.00/hour). The boss requires that the hourly rate be shown for each job on the invoice, so that means it is in a column to where the amount is repeated all the way down. All I want is for the contents of that particular column NOT to show (show as blank), if no job has been entered. In other words, if there is no data entered on that particular row, hide the cont...

Copy one Column Across One Row
Hey guys, I would like to take one column of data and copy it across one row., so, I want the data to go left to right across the spreadsheet instead of top to bottom. If you have a suggestion to solve this, macro or whatever, could you please email it to me at: krea@dslextreme.com thanks, kevin rea Kevin If the column contains no more than 255 rows of data(256 if you are pasting below row 256) you can copy it and select B1 and Paste Special>Transpose>OK>Esc. Gord Dibben Excel MVP On Wed, 14 Apr 2004 17:23:46 -0700, <krea@dslextreme.com> wrote: >Hey guys, > &g...

XML Serialisation & Circular References
I have been able to get simple circular references to be serialized in xml by using the ImportTypeMapping method on the SoapReflectionImporter class. But I am unable to serialise circular references when the circular reference is contained with in a collection class, specifically I am using a custom ArrayList object. I keep getting a StackOverFlow Exception from the XmlSerializer class when attempting the serialisation. The classes are: Class A, Class B - this is derived from System.Collection.ArrayList Class C. Class A contains an instance of B Class B contains multiple instances of C Cl...

Totals in Stacked Column?
I can't display the totals in a stacked column chart. I'm trying to show the total amounts for each column but the data labels only apply to each series. Never mind - Andy Pope's website had the answer. "EllenM" wrote: > I can't display the totals in a stacked column chart. I'm trying to show the > total amounts for each column but the data labels only apply to each series. ...

XSLT, XMl
I have small problem with XslTransformation. I get from WebService xml document. I have xslt and I want transform xml document to html code. It's look easy but I cant't manage with xPath. Maybe someone help me with that. I have problems with xPath in xslt file. I can't navigate by names only by vertical and horizontal axis. What's wrong .... --- Code --- // WebService XmlForAnalysis.Xmla xa = new XmlForAnalysis.Xmla(); xa.Url = urlXmla; XmlForAnalysis.Properties properties = new XmlForAnalysis.Properties(); properties.Content = XmlForAnalysis.Content.Data; // Result Xml...

Merging XML Documents (with ADO.NET?)
I have got 2 XML documents, both of which conform to the same XSD Schema, which define possible optional elements. The 2 XML documents contain 2 disjoint set of XML elements. What is the best, easiest, most efficient way of merging the 2 XML Documents? Can I use DataSet.Merge() facility in ADO.NET?? Any pre-requisites? Any other suggestions? Patrick, Can you provide an example of each XML document? Its not clear to me how the schema can be the same if each XML document has different sets of XML elements. Also, you didn't indicate what you wanted to do after merging the XML ...

Creating Labels, Missing Column
I'm trying to create address labels. In my file I have the columns for "Street Address", "City", "State", "Zip Code" and "Country". The street address does not show up in the window to select what info I want on the label. Anyone know how to fix this??? Hi In your table you "may" have IDfield, 1stName, 2ndName, Street Address, City, State, Zip Code and Country. Create a query based on the table. Bring all the fields in the query and create a calculted culumn with something like Capital: Left([1stName],1) Create a new re...

How to update a portion of rows and columns between two files
I have a Master file with 20 columns of data for each of approximately 700 rows. Each month, I receive an update file that I need to use to update 10 columns of data for 3/4 of the rows in my Master file. There is a unique identifier in each file. Not all rows in the update file will be copied into the Master file and not all rows in the Master file will have updates. What is the best way to do this? I am familiar with VLookup. Shall I write aVLookup for each of the 10 columns in each row that need to be replaced so that I can grab the cell from the new file? Or, is there an easier way? ...

Clustered column graph with mixed data in 2nd column
I'm trying to create a clustered column graph with mixed data in the 2nd column and I cannot find a way to do it. Any suggestions? What's "mixed data"? Do you mean you want to build a stacked column for the second column in the cluster? If so, look here: http://peltiertech.com/Excel/ChartsHowTo/ClusterStack.html - Jon ------- Jon Peltier, Microsoft Excel MVP Tutorials and Custom Solutions Peltier Technical Services, Inc. - http://PeltierTech.com _______ "drhatt" <drhatt@discussions.microsoft.com> wrote in message news:648BC5CE-4DE9-433C-A824-325B6995D...

Columns on wrong side
When I open a book in excel, why is column A in Excel on the right side of the sheets, meaning it looks like this: P-O-N-M-L-K-J-I-H-G-F-E-D-C-B-A How do I change it to look the normal way from left to right when I open a new book in excel? Hi Seems you have set Excel to read from Right to Left - as is done in Arabic language. To set it right Go to menu Tools->Options Choose the International Tab In Right-to-Left Default direction choose Left-to-Right The order of column will be A-B ... Regards Sukhjeet "Drew" wrote: > When I open a book in excel, why is column A in Exce...

Export to XML question
Hi All, The below is a test code to export xml file. The fields Comment and Tip hold xHTML code. The problem occurs if I add the Tip field then I get the following error: The XML page cannot be displayed Required white space was missing. Error processing resource 'file:///C:/1.xml'. Line 1, Position 646 It seems that XM file cannot fully exported and some text is missing. I apprecaite any input. DECLARE @SQL VARCHAR(1024) DECLARE @sqlFlds1 VARCHAR(225) DECLARE @sqlFlds2 VARCHAR(225) DECLARE @sqlFlds3 VARCHAR(225) DECLARE @sqlFlds4 VARCHAR(225) DECLARE @sqlSt...

Checkbox column #2
Hi, How do I create a checkbox column to contain boolean values ? Regards Bo "Bo Rasmussen" <krogenlund@hotmail.com> wrote in news:OtsOMgl6DHA.3648 @TK2MSFTNGP11.phx.gbl: > How do I create a checkbox column to contain boolean values ? > Excel doesn't support this directly. To get a checkbox you need to use VBA Forms or OLE controls, create a bunch of checkboxes, then link them to the cells. Check out View/Toolbars/Forms and View/Toolbars/Control Toolbox. Could you describe in more detail what you're looking for? -- My email address has an extra @ (s...

Wrapping text in column
In Excell 2007, how do you set a column to wrap text? I tried it and even though it seems to allow me to do it when I select column and check wrap text from Format Cells, it doesn't work. It only works when I select one cell and select wrap text. This is a bit irritating as I have many cells in a column to do this to. Thanks, Tom I find that this happens when I paste from Word. If I have the fields set as Vertical/Top and Wrap Text - then I paste any data from Word, it goes to Vertical/Bottom and NOT wrap text. If I paste data from my Textpad program that spans multiple line...

Xml Serialization problem...
Hi, I am trying to use xml serialization to simplify load/save functions in some classes i have created and am hitting a few problems. Any help to either would be most appreciated. I have created a MasterShape class which contains a name, and a 'Shapes' class object, which itself uses the ICollection interface to provide a class which is basically an array of shapes i derive from an abstract base class AbShape, for example i derive Rectangle and Circle from AbShape and wish to be able to store any combination of these shapes.. The problems.. 1) As far as i know classes which imple...

How do I make multi column stacked graphs in Excel
-- Ed Hi, See the links on Jon's page for Cluster Stacked charts. http://peltiertech.com/Excel/ChartsHowTo/ClusterStack.html Cheers Andy Ed B wrote: ...

Subtotaling on column with IF statement results
I created a spreadsheet with one column having an IF statement - it calculates how much we should re-order per store based on what was sold. I asked it to subtotal for each store - the formula appears in the cell, but it does not calculate the subtotal. I tried saving the column as the values, but it still does not subtotal. When I typed in the numbers, it DID subtotal. What do I need to do so it will subtotal? Thanks for your help. -- STK By any chance are you importing the data from another application? Check out your numbers: does the cell contain an apostrophe and then the numb...

Microsoft Project Portfolio Server
Attempting to configure the mapping templates in the Project Server Gateway - Attribute Mapping Template Management. I am able to create a new template, and my fields from PPS appear, but the dropdown menu to pick a corresponding field from Project Server, is displaying "none" for each and every field/attribute (40+ attributes). Appreciate any guidance. Thanks ! Kim On Nov 30, 1:39=A0pm, Kim <khubbard0...@gmail.com> wrote: > Attempting to configure themappingtemplates in the Project Server > Gateway -AttributeMappingTemplate Management. > > I...

Lines Between Columns
Publisher 2003 I have a newsletter page that is formatted to be double column. I want to place a 0.5 point line between the columns. Right clicking within the double columns then clicking on format text box>colors and lines then clicking the box in preview that is for the center line only nothing happens to the menu on the left. The "dashed", "style" and "weight " boxes are grayed out. Out of the six boxes shown there, the only two that activate the above quoted boxes are the two on the right of the bottom row (frame and frame with line down the middle). I ...

stop returning column headings from DB query
I put together a query to go against Oracle that returns a block of data to the spreadsheet. Is there an option somewhere to have the "Return Data to Excel" do so without also returning the column headings? I want the data only. thanks - Russ There are 2 places that you can change that setting..... 1)When you return data from MS Query the dialog where you select the location for the data has a Properties button. Click that button UNcheck: Include Field Names.......click [OK] Continue selecting the query destination OR 2)After the data has been pulled from Oracle Right-click...

Incrementing/decrementing column characters using only worksheet functions?
How can I increment and decrement column characters/letters using worksheet functions? I have a list of 5 characters corresponding to columns. The first character might be A, for column 1. How can I get the second character in the list to automatically configure itself to be B, the third C, the fourth D and the fifth E? That is, I want to set this up so that the second character is linked to the first, the third to the second and so on. That way if I change the first character from A to D then the second character in the list will automatically become E, the third will change to F, the f...

Most efficient method of searching large xml document
I am looking for the most efficient way of searching a large xml document (> 14mg). If I could get some pointers in the right direction. I am using VB.NET. It is readonly. Jim Kitterman wrote: > I am looking for the most efficient way of searching a large xml > document (> 14mg). If I could get some pointers in the right > direction. I am using VB.NET. It is readonly. If you don't need sophisticated querying such as XPath, just take XmlTextReader. -- Oleg Tkachenko [XML MVP, XmlInsider] http://blog.tkachenko.com XmlReader approach is the most performant and resour...

Locking rows (not columns)?
Hi I download and store my bank statements in an Excel spreadsheet. This is maintained in conventional 'bank statement' format; ie columns for date, payee, amount, account balance, with one statement entry per row in chronological order. I find it very useful to be able manipulate the spreadsheet eg by sorting alphabetically by payee, so I can easily see all payments made to a particular company grouped together. However, it's very easy to use the 'sort' function incorrectly, so that the date/payee/amount columns become completely dissociated from each other, and if some...