Click here to Skip to main content
15,896,328 members
Articles / Web Development / ASP.NET

Xml Editor: Work with DataTable, DataView and DataGrid

Rate me:
Please Sign up or sign in to vote.
3.00/5 (8 votes)
2 Oct 2006 39.1K   525   17  
Lets Work with XML, DataTable, DataView and DataGrid
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using jeffTools;

namespace vigortecWeb
{
	/// <summary>
	/// BackEnd ���K�n�y�z�C
	/// </summary>
	public class BackEnd : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.DataGrid DataGrid1;
		jeffTools.XMLtools _xmlt = new XMLtools();
		jeffTools.fileRnW _frw = new fileRnW();
		jeffTools.textValidation _tV = new textValidation();

		#region Setting Strings
		string _filePath = "";
		string _xmlStyle ="";
		string _XMLdtTag = "";
		protected System.Web.UI.WebControls.LinkButton LinkButton1;
		protected System.Web.UI.WebControls.Literal LWarning;
		string _XMLdrTag = "";
		protected System.Web.UI.WebControls.TextBox TB_newDrPosition;
		protected System.Web.UI.HtmlControls.HtmlInputHidden newRowFlag;
		string _SessionName ="xmlTable";
		#endregion
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// �b�o�̩�m�ϥΪ̵{���X�H��l�ƺ��
			setUp();
			if(!Page.IsPostBack)
			{
				initial();
			}
		}

		#region Web Form �]�p�u�㲣�ͪ��{���X
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: ���� ASP.NET Web Form �]�p�u��һݪ��I�s�C
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// �����]�p�u��䴩�ҥ�������k - �ФŨϥε{���X�s�边�ק�
		/// �o�Ӥ�k�����e�C
		/// </summary>
		private void InitializeComponent()
		{    
			this.LinkButton1.Click += new System.EventHandler(this.LinkButton1_Click);
			this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
			this.DataGrid1.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.DataGrid1_SortCommand);
			this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
			this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
		
		#region initial
		private void initial()
		{
			initialSession();
			databind();
		}

		private void setUp()
		{
			string fileName = "XML\\";
			if(Request["fcuk"] != null)
			{
				fileName += Request["fcuk"].ToString();
				this._SessionName += Request["fcuk"].ToString();
			}
			this._filePath = Server.MapPath(fileName);
			this._xmlStyle="";
			this._XMLdtTag = "Menu";
			this._XMLdrTag =  "Items";
			this.LWarning.Text = "";
		}

		private void initialSession()
		{
			DataTable dt = this._xmlt.getDtFromXml(this._filePath, 0);
			this.Session[_SessionName] = dt;
		}

		#endregion

		#region XML functions
		private void dTtoXml(DataTable dt, string filePath, string stylePI, string XMLdtTag, string XMLdrTag)
		{
			//System.IO.StreamWriter _sw = new System.IO.StreamWriter(filePath, false);
			//Response.Write(dt.Columns.GetType().ToString());
			XmlTextWriter xtw = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
			xtw.Formatting = Formatting.Indented;
			xtw.WriteStartDocument();
			xtw.WriteProcessingInstruction("xml-stylesheet", stylePI);
			xtw.WriteStartElement(XMLdtTag);
			for(int i =0; i<dt.Rows.Count; i++)
			{
				drToXml(xtw, dt.Columns, dt.Rows[i], XMLdrTag);
			}
			xtw.WriteEndElement();
		
			xtw.Close();
		}

		private void drToXml(XmlTextWriter xtw, DataColumnCollection dtc, DataRow dr, string XMLdrTag)
		{
			xtw.WriteStartElement(XMLdrTag);
			for(int i =0; i < dtc.Count; i ++)
			{
				this.colToXml(dtc[i],xtw, dr[i].ToString());
			}
			xtw.WriteEndElement();
		}

		private void colToXml(DataColumn dc, XmlTextWriter xtw, string valueS)
		{
			xtw.WriteStartElement(dc.ColumnName);
			xtw.WriteString(valueS);
			xtw.WriteEndElement();
		}

		#endregion

		private DataTable takeOutDt()
		{
			DataTable dt = (DataTable) this.Session[_SessionName];
			return dt;
		}

		private void throwBackDt(DataTable dt)
		{
			this.reorderId(dt);
			this.Session[_SessionName] = dt;
		}
		
		private void reorderId( DataTable dt )
		{
			for(int i =0; i < dt.Rows.Count ; i ++)
			{
				dt.Rows[i]["Id"] = i;
			}
		}

		private void databind()
		{
			DataTable dt = this.takeOutDt();
			this.DataGrid1.DataSource = dt.DefaultView;
			this.DataGrid1.DataBind();
		}
		
		protected void edit(object sender,DataGridCommandEventArgs e) 
		{
			//Response.Write("OK");
			this.DataGrid1.EditItemIndex=e.Item.ItemIndex; 
			this.databind();
		} 

		protected void cancel(object sender,DataGridCommandEventArgs e) 
		{
			if(this.isNewRow())
			{
				DataTable dt = this.takeOutDt();
				dt.Rows.RemoveAt(this.DataGrid1.EditItemIndex);
				this.throwBackDt(dt);
				this.newRowFlag.Value = "0";
			}
			this.DataGrid1.EditItemIndex=-1; 
			this.databind(); 
		} 

		protected void update(object sender,DataGridCommandEventArgs e) 
		{
			DataTable dt = this.takeOutDt();
			this.DataGrid1.DataSource = dt.DefaultView;
			DataView o = (DataView)this.DataGrid1.DataSource;
			for(int i=0; i<o.Table.Columns.Count; i++)
			{
				updateCell(i,o.Table.Rows[this.DataGrid1.EditItemIndex],e);
			}
			dTtoXml(o.Table, this._filePath,this._xmlStyle, this._XMLdtTag,this._XMLdrTag);
			this.DataGrid1.EditItemIndex=-1; 
			this.DataGrid1.DataSource = o.Table;
			this.DataGrid1.DataBind();
		}

		private void updateCell(int nCol,  DataRow _dr, DataGridCommandEventArgs e)
		{
			try
			{
				if(nCol <1)
				{
					_dr[nCol] = this.DataGrid1.EditItemIndex;
				}
				else
					_dr[nCol]=((TextBox)e.Item.Cells[nCol+6].Controls[0]).Text;
			}
			catch(Exception exp)
			{
				Response.Write(nCol);
			}
		}

		private void Button1_Click(object sender, System.EventArgs e)
		{
			this.addNewRow();
		}
		
		private void addNewRow()
		{			
			if(this.isGoodIndex( TB_newDrPosition.Text))
			{
				int newRp = int.Parse(TB_newDrPosition.Text);
				DataTable dt = (DataTable) this.Session[this._SessionName];
				DataRow dr = dt.NewRow();
				dr["Id"] = newRp;
				dt.Rows.InsertAt(dr,newRp);
				this.reorderId(dt);
				this.Session["xmlTable"] =dt;
				DataView dv = dt.DefaultView;
				dv.Sort = "Id";
				this.newRowFlag.Value = "1";
				this.DataGrid1.DataSource = dv;
				this.DataGrid1.EditItemIndex = newRp;//dt.Rows.Count-1;
				this.DataGrid1.DataBind();
			}
			else
			{
				this.LWarning.Text = "<a class='warning' >Bad Index Input </a>";
			}
		}

		private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			int deleteIndex = e.Item.ItemIndex;
			DataTable dt = this.takeOutDt();
			dt.Rows.RemoveAt(deleteIndex);
			reorderId(dt);
			dTtoXml(dt, this._filePath,this._xmlStyle, this._XMLdtTag,this._XMLdrTag);
			this.DataGrid1.DataSource = dt.DefaultView;
			this.DataGrid1.DataBind();
		}	

		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{	
		}

		private void LinkButton1_Click(object sender, System.EventArgs e)
		{
			this.addNewRow();
		}

		private void SwitchRows(DataTable _dt, int i, int j)
		{
			object[] _iRow = _dt.Rows[i].ItemArray;
			object[] _jRow = _dt.Rows[j].ItemArray;

			_dt.Rows[i].ItemArray = _jRow;
			_dt.Rows[j].ItemArray = _iRow;
		}

		private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			int selectedIndex = e.Item.ItemIndex;
			DataTable dt = this.takeOutDt();//(DataTable) this.Session[_SessionName];
			switch(e.CommandName.Trim())
			{
				case "SelectUp":
					if(selectedIndex == 0)
					{
						this.LWarning.Text = "<a class='warning' >Top row can not be moved up, there is no heaven</a>";
					}
					else
					{
						this.SwitchRows(dt,selectedIndex, selectedIndex-1);
					}
					//Response.Write("UP");
					break;
				case "SelectDown":
					if( selectedIndex == dt.Rows.Count-1)
					{
						this.LWarning.Text = "<a class='warning' >Botton Row can not be moved down, there is no hell</a>";
					}
					else
					{
						this.SwitchRows(dt,selectedIndex, selectedIndex+1);
					}
					//Response.Write("Down");
					break;
				case "SelectGoto":
					string _index = ((TextBox)e.Item.FindControl("gotowhere")).Text;
					if(this.isGoodIndex(_index))
					{
						int index = int.Parse(_index);
						this.dtGoTo(dt, selectedIndex, index);
					}
					break;
			}
			this.throwBackDt(dt);
			dTtoXml(dt, this._filePath,this._xmlStyle, this._XMLdtTag,this._XMLdrTag);
			DataView dv = dt.DefaultView;
			dv.Sort = "Id";
			this.DataGrid1.DataSource = dv;
			this.DataGrid1.DataBind();
		}
		private void dtGoTo(DataTable dt , int curI, int newI)
		{
			//dt.Rows
			DataRow holder = copyRowAt(curI, dt);
			dt.Rows.RemoveAt(curI);
			this.reorderId(dt);
			dt.Rows.InsertAt(holder, newI);
			this.reorderId(dt);
			this.throwBackDt(dt);
			dTtoXml(dt, this._filePath,this._xmlStyle, this._XMLdtTag,this._XMLdrTag);
			this.DataGrid1.DataSource = dt.DefaultView;
			this.DataGrid1.DataBind();
		}

		private DataRow copyRowAt(int _i, DataTable dt )
		{
			DataRow _dr = dt.NewRow();
			for( int i =0; i < dt.Columns.Count ; i++)
			{
				_dr[dt.Columns[i]] = dt.Rows[_i][dt.Columns[i]].ToString();
			}
			return _dr;
		}

		private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			
		}

		private bool isNewRow()
		{
			return this.newRowFlag.Value.Trim().Equals("1");
		}

		private bool isGoodIndex(string _index)
		{
			bool _bool = false;
			if(_tV.isDigitalOnly(_index) )//&&  )
			{
				int INT_index = int.Parse(_index);
				if( INT_index >=0 && INT_index < this.takeOutDt().Rows.Count+1)
					_bool =  true;
			}
			return _bool;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions