Click here to Skip to main content
Click here to Skip to main content
Articles » Database » Database » SQL Server » Downloads
 
Add your own
alternative version

Using SQL Server Metadata and Statistics to Build a Table Explorer Application

, 1 Oct 2012 CPOL
Develops an analogy between database table and file directory information and argues that it could be very useful if it were possible to have a similar application to Windows Explorer for database tables. Demonstrates how to obtain the information from Sql Server system tables and dynamic management
using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;

/*
	Schedule of work.
	4. Add generate grovelling message tp DBA's
	3. Add fallback code 
	1. Remove surplus options 
		remove context menu from tables
		remove main menu options
		help about - port from DbViewSharp
*/

namespace DbView
{
	public delegate void CancelDelegate();

	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public partial class MainForm : System.Windows.Forms.Form
	{
		public enum DisplayType
		{
			Unknown = -1, CustomView, Tables, Profile
/*
			Views, Procs, Triggers,
			Structure, , History, Permissions,
			MessageProfile, Aggregate, Functions, Jobs, FieldMetaData,
			Calculated, Dependencies, Processes, Locks, ServiceBroker,
			SqlTemplate, JobSteps
*/
		};
		// view object cache in case there is a cost to set-up
		Dictionary<DisplayType, DbViewBase> m_Views;


		//////////////////////////////////////////////////////////////
		// New - state for tables report
		


        private MruMenu mruMenu;
        private Model m_Model;
	    private GridStateList m_Navigation;
        private Hashtable m_HTText;        // holds current search text for each view type

        private bool m_ViewDirty = false;  // edits made to current grid
        private String m_strLastSearchTextUsed = "";   // holds last search text
        // MessageProfile option is Obsolete specialised function
        DisplayType m_DisplayType = DisplayType.Tables; 

		// New. Save current grid state
		GridState m_CurrentState;
		GridState m_NewState;

		// copy table state
		private String lastCopyConn = "";
		private String lastCopyTgtConn="";

		// Field Picker internals
        String m_Table;
        String m_MatchString;
        ArrayList m_TableFieldList;
		bool m_FieldPanelActive = false; // preserve state for the table view
		// on start up
		private String m_StartupConnectionTag;
		// threading
		enum threadstate {none, working, done, cancelled, errored};
		threadstate m_Threadstate = threadstate.none;
		DbViewBase m_vbCustom;
		DataFetchWorker m_CurrentDataThread = null;
		CancelOpForm m_CancelWorkForm;
		bool m_WorkingDialogDisplayed = false;
        // end
		//////////////////////////////////////////////////////////////////////////
		// Public items for use by views.
		//////////////////////////////////////////////////////////////////////////
		public DataGridView Grid { get { return this.results; }}
		public Model Model { get { return this.m_Model; }}
		public DataSet Data { get { return this.theDset; } }
		public void Refresh() 
		{	
			Go_Click(this, new System.EventArgs()); // simulate GO button press
		}
		// This demo only has table grids so this should be safe
		DbViewSample TableView {get { return this.m_Model.DbView as DbViewSample; } }
		 
		//////////////////////////////////////////////////////////////////////////
		// End items for use by views
		//////////////////////////////////////////////////////////////////////////
		#region Start-up / Shut-downcode
        //
        // ************** Start-up / Shut-down ************************
        // 
		public MainForm(String StartupConnectionTag)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
            m_Model = new Model(Application.UserAppDataPath, this);
            m_Navigation = new GridStateList();
    	    m_HTText = new  Hashtable();
			m_Views = new Dictionary<DisplayType,DbViewBase>();
            m_CancelWorkForm = new CancelOpForm(new CancelDelegate(cancelFetch));
            //m_Tables = new DbViewSample(this.m_Model, this.results);
            init_mru();
                        
            // this.update_popup_menu(); // adds right-click options for first view.
            // store for later when showing the form
			// intialise state
/*
			m_CurrentState = new GridState("", DisplayType.Tables);
			// possibly tag below for removal
			m_StartupConnectionTag = StartupConnectionTag;
			m_CurrentState.m_connection_tag = StartupConnectionTag;
			m_NewState = new GridState(m_CurrentState);
*/
			m_CurrentState = new GridState("", DisplayType.Tables);
			m_NewState = new GridState("", DisplayType.Tables);
			// possibly tag below for removal
			m_StartupConnectionTag = StartupConnectionTag;
			m_NewState.m_connection_tag = StartupConnectionTag;
		}
        
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

        private void init_mru()
        {
            const String regkey_name = "SOFTWARE\\Dealogic\\DbView";
            mruMenu = new MruMenuInline(fileMru, new MruMenu.ClickedHandler(OnMenuFileMru), String.Format("{0}\\MRU", regkey_name), 8);
            // remove missing Connections
            ConnectionListMgr cl = m_Model.ConnectionList;
            for (int idx = mruMenu.NumEntries-1; idx >= 0; --idx)
            {
                String strName = mruMenu.GetFileAt(idx);
                try 
                {
                    connInfo ci = cl[strName];
                }
                catch (DbViewApplicationException e)
                {                
                    mruMenu.RemoveFile(strName);
                }                    
            }
        }    
        
        private void IDontDoThatAnyMore(object sender, System.EventArgs e)
        {
			MessageBox.Show(this, "Feature not implemented", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		}

        private EventHandler[] get_handler_list()
        {
            EventHandler[] handler_list = new EventHandler[17];
            handler_list[0] = new EventHandler(dataAddView_Click);
            handler_list[1] = new EventHandler(IDontDoThatAnyMore);
            handler_list[2] = new EventHandler(IDontDoThatAnyMore);
            handler_list[3] = new EventHandler(actionProfile_Click);
            handler_list[4] = new EventHandler(actionProfileAll_Click);
            handler_list[5] = new EventHandler(actionGoto_Click);
            handler_list[6] = new EventHandler(dataChangeView_Click); 
            handler_list[7] = new EventHandler(actionFind_Click); 
            handler_list[8] = new EventHandler(IDontDoThatAnyMore);
            handler_list[9] = new EventHandler(actionAggregated_Click);
            handler_list[10] = new EventHandler(IDontDoThatAnyMore);
            handler_list[11] = new EventHandler(IDontDoThatAnyMore);
            handler_list[12] = new EventHandler(IDontDoThatAnyMore);
            handler_list[13] = new EventHandler(IDontDoThatAnyMore);
            handler_list[14] = new EventHandler(IDontDoThatAnyMore);
			handler_list[15] = new EventHandler(IDontDoThatAnyMore);
			handler_list[16] = new EventHandler(IDontDoThatAnyMore);
			return handler_list;
        }
    
        // end of shut-down code
        #endregion

        #region helpers
        private void SetWindowTitle(String connection)
        {
            int iPos = this.Text.IndexOf(':');
            String old = (iPos == -1) ? this.Text : this.Text.Substring(0, iPos);
            this.Text = String.Format("{0}: [ {1} ]", old, connection);
        }

        private connInfo GetConnectionInfo()
        {
            String connName = m_NewState.m_connection_tag;
            return this.m_Model.ConnectionList[connName];    
        }
        private void UpdateStatusBar(connInfo ci)
        {
            String s = "";
            if (ci.Server != null)
                s = String.Format("{0}.{1}", ci.Server, ci.Database); 
        }
        
        private String GetTableName()
        {
			// if requesting table name when dat is display hack the name out of the tool bar
			if (m_CurrentState.m_DisplayType == DisplayType.CustomView)
				return this.statusBar1.Panels[1].Text;
			DataRow row;
            this.getSelectedRow(out row);
            String table_name = row[0].ToString();
            return table_name;
        }
        /* Obsolete feature
        private String get_search_text()
        {
            DbViewBase vb = this.m_Model.DbView;
            if (m_DisplayType > DisplayType.CustomView)
            {
                if (m_HTText.ContainsKey(m_DisplayType))
                    return (String)m_HTText[m_DisplayType];
            }
            else
            {
                String strKey = vb.GetType().ToString();
                if (m_HTText.ContainsKey(strKey))
                    return (String)m_HTText[strKey];
                
            }
            return "";
        }

        private void set_search_text(String strText)
        {
            m_Model.NamePart = strText; // new. Update model
            this.comboSearchPart.Text = strText;
            DbViewBase vb = this.m_Model.DbView;
            if (m_DisplayType > DisplayType.CustomView)
                m_HTText[m_DisplayType] = strText;
            else
            {
                String strKey = vb.GetType().ToString();
                m_HTText[strKey] = strText;
            }
        }
		*/ 
        private String make_status_pane_text(DbViewBase vb)
        {
            String table_name = (vb.ViewParams.IsTypedClass) ? vb.Title : vb.ViewParams.Table;
            return table_name;
        }
		/* recently commented out.
        private String make_filter_pane_text(DbViewBase vb)
        {
            String text = "";
            if (m_DisplayType == DisplayType.CustomView)
            {
                text = ((DbConfigurableView)(vb)).ViewParams.FilterClause;
            }
            
            return text;
        }
        */
        private void UpdateFilterPanel(DbViewBase vb)
        {
            int FilterPanel = 3; // ie. 4th visible panel
            String text = "";
			//if (m_CurrentState.m_DisplayType == DisplayType.CustomView)
			//{
			//    text = ((DbConfigurableView)(vb)).ViewParams.FilterClause;
			//    statusBar1.Panels[FilterPanel].Text = String.Format("Filter:[ {0} ]", text);
			//}
			//else
                statusBar1.Panels[FilterPanel].Text = text;
        }

        private void SetEditSubMenuState()
        {
            DbViewBase vb = this.m_Model.DbView;
            ActivateReadOnly(vb);
        }
        
		//FieldInfo GetColumnInfo(DataTable dt, String FieldName)
		//{
		//    TableSchema ts = new TableSchema(m_Model, dt.TableName);
		//    ts.Populate();
		//    return ts[FieldName];
		//}

/*
        private int getSelectedRow(out DataRow selectedRow)
        {
            // this ensures that you get the current row even when it is sorted.
            CurrencyManager cm = (CurrencyManager)results.BindingContext[results.DataSource, ""];
            DataRowView dr = (DataRowView)cm.Current;
            selectedRow = dr.Row;
            DataTable dt = theDset.Tables[0];
            for (int idx = 0; idx < dt.Rows.Count; ++idx)
            {
                if (dt.Rows[idx] == selectedRow)
                    return idx;
            }
            return 0;
        }
*/
        private int getSelectedRow(out DataRow selectedRow)
        {
            return Helper.getSelectedRow(results, out selectedRow);
        }
        
        private int getTwoSelectedRows(out DataRow selectedRow1, out DataRow selectedRow2)
        {
            selectedRow1 = null;
            selectedRow2 = null;
            // this ensures that you get the current row even when it is sorted.
            DataRowView rv;

            DataTable dt = theDset.Tables[0];
            int selectionCount = 0;
            for (int i = 0; i < results.Rows.Count; ++i)
            {
                if (results.Rows[i].Selected)
                {
                    if (selectionCount == 0)
                    {
                        rv = (DataRowView)results.Rows[i].DataBoundItem;
                        selectedRow1 = rv.Row; 
                    }
                    else
                    {
                        rv = (DataRowView)results.Rows[i].DataBoundItem;
                        selectedRow2 = rv.Row;
                    }
                    ++selectionCount;
                }
            }
            return selectionCount;
        }



        private void displayExceptionMessage(DbViewApplicationException ex, String source)
        {
            String message = String.Format("Source: {0}\n\nMessage: {1}", source, ex.Message);
            MessageBox.Show(message, "Problem Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #endregion

        #region form logic
        
            

        private void setEditMenuState()
        {
        }
        
		//private void setShowMenuState(object sender, System.EventArgs e)
		//{
		//    bool enable = false;
		//    // only allow fields when tables are shown
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? true : false;
		//    this.actionStructure.Enabled = enable;
		//    // only allow data when views or tables are shown
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? true :
		//        (m_CurrentState.m_DisplayType == DisplayType.Views) ? true : 
		//        false;
		//    this.actionData.Enabled = enable;
		//    //
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.CustomView) ? true : false;
		//    this.actionAggregated.Enabled = enable;
		//}

		//private void setActionState(object sender, System.EventArgs e)
		//{
		//    bool enable = false;
		//    // only allow profile when tables are shown
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.CustomView) ? true : false;
		//    this.actionProfile.Enabled = enable;
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.Procs) ? true :
		//             (m_CurrentState.m_DisplayType == DisplayType.Functions) ? true :
		//             (m_CurrentState.m_DisplayType == DisplayType.Views) ? true : false;
		//    this.actionSearchSource.Enabled = enable;                     
		//}

		//private void setFavouritesState(object sender, System.EventArgs e)
		//{
		//    bool enable = false;
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? true :
		//             (m_CurrentState.m_DisplayType == DisplayType.Procs) ? true :
		//             (m_CurrentState.m_DisplayType == DisplayType.Views) ? true : false;
		//    this.favouritesAdd.Enabled = enable;
		//}

		//private void setToolsMenuState(object sender, System.EventArgs e)
		//{
		//    bool enable = false;
		//    enable = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? true : false;
		//    this.toolsFieldSelector.Enabled = enable;
		//    this.toolsCopyTable.Enabled = enable;
		//}
        
		//private void menuEditEdit_Click(object sender, System.EventArgs e)
		//{
		//    // if a custom view then check whether Pkeys are in the view.
		//    if (this.m_CurrentState.m_DisplayType == DisplayType.CustomView)
		//    {
		//        String message = "";
		//        TableSchema ts = new TableSchema(m_Model, theDset.Tables[0].TableName);
		//        ts.Populate();
		//        bool bNoPkey = true;
		//        int pkeyCount = 0;
		//        for (int fIdx = 0; fIdx < ts.Count; ++fIdx)
		//        {
		//            FieldInfo fi = ts[fIdx];
		//            if (fi.IsPKey)
		//                ++pkeyCount;
		//        }
		//        if (pkeyCount == 0)
		//        {
		//            message = String.Format("Cannot edit table {0}. The table has no primary key", theDset.Tables[0].TableName);
		//            MessageBox.Show(message);
		//            return;
		//        }                
		//        String Missing = "";
		//        for (int fIdx = 0; fIdx < ts.Count; ++fIdx)
		//        {
		//            FieldInfo fi = ts[fIdx];
		//            if (fi.IsPKey)
		//            {
		//                bool bkeyFound = false;
		//                for (int idx = 0; idx < this.results.Columns.Count && !bkeyFound; ++idx)
		//                {
		//                    if (results.Columns[idx].HeaderText.CompareTo(fi.Name) == 0)
		//                        bkeyFound = true;
		//                }
		//                if (!bkeyFound)
		//                    Missing += String.Format("{0} ",fi.Name);
		//            }
		//        }
		//        if (Missing.Length > 0)
		//        {
		//            message = String.Format("Cannot edit table {0}. Primary key(s) {1} missing from the view", theDset.Tables[0].TableName, Missing);
		//            MessageBox.Show(message);
		//            return;
		//        }
		//    }
		//    //            
		//    DbViewBase vb = this.m_Model.DbView;
		//    vb.IsReadOnly = !vb.IsReadOnly;
		//    SetEditSubMenuState();
		//}


        private void setDataState(object sender, System.EventArgs e)
        {
            bool enable = false;
            // only allow profile when tables are shown
            enable = (m_CurrentState.m_DisplayType == DisplayType.CustomView) ? true : false;
//            this.dataChangeView.Enabled = enable;
            //this.dataFilter.Enabled = enable;
            enable = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? true : false;
//            this.dataAddView.Enabled = enable;
        }

        private void setNavigateState(object sender, System.EventArgs e)
        {
            bool enable = false;
            // only allow goto when in history
//            enable = (m_CurrentState.m_DisplayType == DisplayType.History) ? true : false;
            //this.navigateGoto.Enabled = enable;
        }
/*        
        private void saveState_Old()
        {
			if (m_CurrentState.m_connection_tag.Length == 0)
				return; // bootstrap current state ie. not valid for history
            if (this.m_CurrentState.m_DisplayType == DisplayType.History)
                return; // do not save history state (no point)
            // get current connection
            String connection_tag = this.m_NewState.m_connection_tag; 
            DbViewBase vb = this.m_Model.DbView;
            // get the grid view object
            String view_name = (vb == null) ? "" : vb.Title;
            // sort out state here
			GridState g = new GridState(connection_tag, m_DisplayType);
			g.m_view_name = view_name;
            g.m_special_view = (int)this.m_DisplayType;
            g.m_search_text = m_Model.NamePart;
            g.m_grid_row = 0;
            m_Navigation.add(g);
        }
*/
		private void saveState(GridState newState)
		{
			//if (newState.m_DisplayType == DisplayType.History)
			//    return; // do not save history state (no point)
			// get current connection
			GridState g = new GridState(newState);
			m_Navigation.add(g);
		}
		
//        private void setToolbarState()
//        {
//            bool bDataView = (m_CurrentState.m_DisplayType == DisplayType.CustomView);
//            this.tbAggregate.Enabled = bDataView;
//            this.tbSum.Enabled = bDataView;
//            this.tbFilter.Enabled = bDataView;
//            this.tbEditView.Enabled = bDataView;
//            bool bTableView = (m_CurrentState.m_DisplayType == DisplayType.Tables);
//            this.tbFieldSelecter.Enabled = bTableView;
////            this.tbFieldSelecter.Pushed = (this.FieldPanel.Visible);
				
//        }
		
		private DbViewBase getDbView(DisplayType dt)
		{
			DbViewBase vb;
			
			switch (dt)
			{
				//                case DisplayType.Tables: vb = new DbViewSample(this.m_Model, this.results); break;
				case DisplayType.Tables: vb = new DbViewSample(this.m_Model, this.results); break;
				//case DisplayType.Views: vb = new DbUtilViews(this.m_Model, this.results); break;
				//case DisplayType.Procs: vb = new DbUtilProcs(this.m_Model, this.results); break;
				//case DisplayType.Functions: vb = new DbUtilFuncs(this.m_Model, this.results); break;
				//case DisplayType.Jobs: vb = new DbUtilJobs(this.m_Model, this.results); break;
				//case DisplayType.JobSteps: vb = new DbUtilJobSteps(this); break;
				//case DisplayType.Triggers: vb = new DbUtilTriggers(this.m_Model, this.results); break;
				//case DisplayType.Calculated: vb = new DbViewCalculations(this.m_Model, this.results); break;
				//case DisplayType.Dependencies: vb = new DbViewDepends(this.m_Model, this.results); break;
				//case DisplayType.Processes: vb = new DbViewProcesses(this.m_Model, this.results); break;
				//case DisplayType.Locks: vb = new DbViewLocks(this.m_Model, this.results); break;
				//case DisplayType.ServiceBroker: vb = new DbServiceBroker(this.m_Model, this.results); break;
				//case DisplayType.Structure:	vb = new DbViewStructure(GetTableName());break;
				//case DisplayType.FieldMetaData:	vb = new DbViewMetaData(GetTableName());break;
				//// can't have this here as it depends on state
				//// case DisplayType.Profile: vb = new DbProfile(m_Profile; break;
				//case DisplayType.History: vb = new DbHistory(m_Model); break;
				//case DisplayType.Permissions: vb = new DbPermissions(this.m_Model, this.results); break;
				//// can't have this here as it depends on state
				//// case DisplayType.Aggregate: vb = this.m_Aggregate; break;

				case DisplayType.CustomView:
					vb = m_vbCustom;
					// ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
					if (vb == null)
						goto default;
					break;
//				case DisplayType.SqlTemplate: vb = new DbViewSqlTemplates(this); break;
				default:
					throw new DbViewApplicationException("Unhandled DisplayType");
			}
			return vb;
		}
		
		private void UpdateViewCache(DisplayType dt, DbViewBase vb)
		{
			if (m_Views.ContainsKey(dt))
				m_Views[dt] = vb;
			else
				m_Views.Add(dt, vb);
		}

        private void update_popup_menu()
        {
            // remove pop-up from resullts.
            this.results.ContextMenu.MenuItems.Clear();
            DbViewBase vb = this.m_Model.DbView;
            //ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
            if (vb == null)
                return; // ie. new view
            vb.AddPopupItems(this.results.ContextMenu, get_handler_list() );
        }
        
        private void create_link(String view_name)
        {
        /*
            connInfo targetInfo = GetConnectionInfo();
            m_Model.View_LInker.add_link(view_name, targetInfo.Name);
        */
        }
		
		// commit changes should not now clear the dset
        private bool Commit_Changes()
        {
            // skip check if no view
            if (theDset != null)
            {
                DbViewBase vb = this.m_Model.DbView;
                // onclose function should return false to prevent continuation
                if (!vb.OnCloseDataSet(theDset))
                    return false;
                // changes committed appraently. We are good to proceed.
                this.m_ViewDirty = false;
            }                
            return true;
        }

        private bool Commit_Changes_with_confirm(bool bClear)
        {
            // skip check if no view
            if (theDset != null)
            {
                DialogResult res = DialogResult.No; // as if no cancel changes, but there were no changes
                if (this.m_ViewDirty)
                {
                    // only here with active dialog
                    String strMessage = "Changes made - do you wish to save them?";
                    res = MessageBox.Show(this, strMessage, "Save changes",
                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    switch (res)
                    {
                        case DialogResult.Yes: Commit_Changes(); break;
                        case DialogResult.No: break;
                        case DialogResult.Cancel: return false;  // should prevent move?
                    }                
                    this.m_ViewDirty = false;
                }
            }                
            // not sure why clear is necessary, but here for compatibility
            if (bClear)
            {
                // .DataSource = null;
            }
            return true;
        }
 
        private void ActivateReadOnly(DbViewBase vb )
        {
            results.ReadOnly = vb.IsReadOnly;
            results.AllowUserToAddRows = !vb.IsReadOnly;
            results.AllowUserToDeleteRows = !vb.IsReadOnly;
            if (!vb.IsReadOnly)
                theDset.Tables[0].RowChanged += new DataRowChangeEventHandler(MainForm_RowChanged);
            //menuEditEdit.Checked = !vb.IsReadOnly;
        }

		//private void DecorateData()
		//{
		//    // set grid column colours depending on field type
		//    TableSchema ts = new TableSchema(m_Model, theDset.Tables[0].TableName);
		//    ts.Populate();
		//    int freeze = -1;
		//    for (int idx = 0; idx < this.results.Columns.Count; ++idx)
		//    {
		//        String field = this.results.Columns[idx].HeaderText;
		//        FieldInfo fi = ts[field];
		//        if (fi != null)
		//        {
		//            if (fi.IsPKey)
		//            {
		//                this.results.Columns[idx].DefaultCellStyle.BackColor = System.Drawing.Color.Bisque;
		//                if (idx == freeze + 1)
		//                {
		//                    this.results.Columns[idx].Frozen = true;
		//                    ++freeze;
		//                }
		//            }
		//            else if (fi.IsFKey)
		//            {
		//                    this.results.Columns[idx].DefaultCellStyle.BackColor = System.Drawing.Color.Tan;
		//            }
		//            else
		//            {
		//                if (fi.IsIndexed)
		//                    this.results.Columns[idx].DefaultCellStyle.BackColor = System.Drawing.Color.PaleGoldenrod;
		//            }
		//            // 
		//        }
		//    }
		//}
        // check returned dset and trim wide char colunms with blank spaces
        // to squeeze more data into view.
		private void TrimData(DataTable dt)
		{
            // search for string columns.
            foreach (DataColumn dc in dt.Columns)
            {
                if (dc.DataType == typeof(String))
                {
					// don't bother to process data less than the field name length
					int namel = dc.ColumnName.Length;
					foreach (DataRow dr in dt.Rows)
					{
						String source = dr[dc].ToString();
						if (source.Length > namel) // field name length check
							if (source[source.Length-1] == ' ')  // something to do check
								dr[dc] = dr[dc].ToString().Trim(); // replace only where necessary
					}
                }
            }
            // have to spike the changes so that they are not written to the database
            dt.AcceptChanges();
		}
/*		
        private void Table_Search()
        {
            // old was vb. Can use model object now.
            DbViewBase vb = this.m_Model.DbView;
            // test for missing items.
            if (vb == null)
                return; // ie. new view
            if (m_Model.ConnectionString.Length == 0)
                return;
            // do the business.
            try
            {
				String seek = this.comboSearchPart.Text.Trim();
				vb.GetMainDSet(m_Model.ConnectionString, seek, out theDset);
                // truncate if necessary
                TrimData(theDset.Tables[0]);
				m_strLastSearchTextUsed = seek;
                // was before
				// get the text from the control
				// ModelFormControl.SearchTextFromControl(this.m_Model, this.comboSearchPart);
				// above done below now.
				this.set_search_text(seek);
				// update the last seach text used by the current 
				ModelFormControl.UpdateMruCombo(this.comboSearchPart);
				// lazy place to save state. This may not always work.
				// if not then move to event code.
				if (results.CurrentRow != null)
					this.m_Navigation.updateRowState(results.CurrentRow.Index);
				this.saveState();
				// end was before
			}
            catch (SqlException e)
            {
                String ss = e.Message;
                throw new DbViewApplicationException(ss);
            }

            results.Visible = false; // added for render speed. Remove if it proves ugly
            results.DataSource = null;

            // Implement wrapping for Profile or field metadata
            bool WrapMode = (bool)(this.m_DisplayType == DisplayType.Profile ||
                                   this.m_DisplayType == DisplayType.FieldMetaData);
            if (WrapMode)
            {
                results.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                results.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            }
            else
            {
                results.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                results.DefaultCellStyle.WrapMode = DataGridViewTriState.False;
            }
if (theDset.Tables[0].Rows.Count > 500)
	results.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
else
	results.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            //BindingSource to sync DataTable and DataGridView
            BindingSource bSource = new BindingSource();
            // set the BindingSource DataSource
            bSource.DataSource = theDset.Tables[0];
            // set the DataGridView DataSource
            results.DataSource = bSource;
            // prevent edits unless user asks
            ActivateReadOnly(vb);
            // set width
            String sTitle = theDset.Tables[0].TableName;
            // Hack for views. Color in the Pkey and Fkey/Index columns
            if (this.m_DisplayType == DisplayType.CustomView)
                DecorateData();

            results.Visible = true;  // added for render speed. Remove if it proves ugly          
			// field panel logic
			if (this.FieldPanel.Visible && this.m_DisplayType != DisplayType.Tables)
				this.FieldPanel.Visible = false; // turn it off
			if (this.m_DisplayType == DisplayType.Tables && !this.FieldPanel.Visible && this.m_FieldPanelActive)
				this.FieldPanel.Visible = true; // turn it on. will it reset?

            // status bar
            OnRowSelected(0);
            // update table/view panel
            int row_panel = 1;
            statusBar1.Panels[row_panel].Text = make_status_pane_text(vb);
            // filter?
            UpdateFilterPanel(vb);
            setToolbarState();
        }
*/
/*
		// newState is presently the contents of m_NewState
		private void GetGridData(GridState newState)
		{
			// Get view from display type in state
			DbViewBase vb = null;
			// special if data view 
			if (newState.m_DisplayType == DisplayType.CustomView)
			{
				vb = this.m_vbCustom; // ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
			}
			else
			{
				// keep a map of objects for non-custom views.
				if (!m_Views.ContainsKey(newState.m_DisplayType))
					this.m_Views.Add(newState.m_DisplayType, getDbView(newState.m_DisplayType));
				vb = this.m_Views[newState.m_DisplayType];
				if (newState.m_DisplayType == DisplayType.History)
				{
					DbHistory vbh =	(DbHistory)vb;
					vbh.Refresh(this.m_Navigation.getAllHistory()); 
				}
				if (newState.m_DisplayType == DisplayType.JobSteps)
				{
					DbUtilJobSteps vbj = (DbUtilJobSteps)vb;
					vbj.UpdateJobId();
				}
			}
				
			// test for missing items.
			if (vb == null)
				return; // ie. new view
			// get connection info from tag
			connInfo ci = m_Model.ConnectionList[newState.m_connection_tag];
			// and connection string from that
			String connStr = ci.connectionString;
			if (connStr.Length == 0)
				return;
			// do the business.
			try
			{
				DataSet dsCurrent;
				vb.GetMainDSet(connStr, newState.m_search_text, out dsCurrent);
				// not sure whether this is necessary, but ...
				if (this.theDset != null) this.theDset.Dispose(); // explicitly mark for free up.
				// assign the new one 
				this.theDset = dsCurrent;
				// truncate if necessary
				TrimData(theDset.Tables[0]);
				// strighten it up here. Hopefully not wanted for much longer
				m_Model.DbView = vb;
				// end was before
			}
			catch (SqlException e)
			{
				String ss = e.Message;
				throw new DbViewApplicationException(ss);
			}


		}
*/

		private void OnFinishFetchData(DbViewBase vb, DataSet dsCurrent)
		{
			try
			{
				// truncate if necessary
				TrimData(dsCurrent.Tables[0]);
				// not sure whether this is necessary, but ...
				if (this.theDset != null) this.theDset.Dispose(); // explicitly mark for free up.
				// assign the new one 
				this.theDset = dsCurrent;
				// strighten it up here. Hopefully not wanted for much longer
				m_Model.DbView = vb;
				// end was before
				UpdateGridView(this.m_NewState);
			}
			catch (SqlException e)
			{
				// restore previous state
				m_NewState.CopyContent(m_CurrentState);
				String ss = e.Message;
				throw new DbViewApplicationException(ss);
			}


		}
		


		private void UpdateGridView(GridState newState)
		{
			// lazy place to save state. This may not always work.
			// if not then move to event code.
			if (results.CurrentRow != null)
			{
				this.m_Navigation.updateRowState(results.CurrentRow.Index); // schedule for removal
				m_CurrentState.m_grid_row = results.CurrentRow.Index;
			}

			results.Visible = false; // added for render speed. Remove if it proves ugly
			results.DataSource = null;

			// Implement wrapping for Profile or field metadata
			bool WrapMode = (bool)(newState.m_DisplayType == DisplayType.Profile); // || newState.m_DisplayType == DisplayType.FieldMetaData);
			if (WrapMode)
			{
				results.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
				results.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
			}
			else
			{
				results.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
				results.DefaultCellStyle.WrapMode = DataGridViewTriState.False;
			}
			if (theDset.Tables[0].Rows.Count * theDset.Tables[0].Columns.Count > 1000 * 10)
				results.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
			else
				results.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
			//BindingSource to sync DataTable and DataGridView
			BindingSource bSource = new BindingSource();
			// set the BindingSource DataSource
			bSource.DataSource = theDset.Tables[0];
			// set the DataGridView DataSource
			results.DataSource = bSource;
			// prevent edits unless user asks
			ActivateReadOnly(m_Model.DbView);
			this.results.Enabled = true; // renable as it has been disabled for ui feedback
			// set width
			String sTitle = theDset.Tables[0].TableName;
			// Hack for views. Color in the Pkey and Fkey/Index columns
			//if (newState.m_DisplayType == DisplayType.CustomView)
			//    DecorateData();

			results.Visible = true;  // added for render speed. Remove if it proves ugly          
			// field panel logic
			//if (this.FieldPanel.Visible && newState.m_DisplayType != DisplayType.Tables)
			//    this.FieldPanel.Visible = false; // turn it off
			//if (newState.m_DisplayType == DisplayType.Tables && !this.FieldPanel.Visible && this.m_FieldPanelActive)
			//    this.FieldPanel.Visible = true; // turn it on. will it reset?

			////////////////////////////////////////////////
			// set ui state
			// update the pop-up menu if this is a change of type
			if (newState.m_DisplayType != m_CurrentState.m_DisplayType)
				this.update_popup_menu();

			if (newState.m_connection_tag != m_CurrentState.m_connection_tag)
				OnConnected(); // resets certain items follwing reconnection to another DB

			// hold last search for hooky logic when the connection is changed
			// (might not be needed now.
			m_strLastSearchTextUsed = newState.m_search_text;
			// synch search text combo display with what is actually searched
			if (this.comboSearchPart.Text != newState.m_search_text)
				this.comboSearchPart.Text = newState.m_search_text;
			// update the last seach text used by the current 
			ModelFormControl.UpdateMruCombo(this.comboSearchPart); // ok

			// save state into history
			newState.m_view_name = m_Model.DbView.Title;
			this.saveState(newState);

            // Reset source search
            if (newState.m_search_source)
            {
                newState.m_search_text = "";
                newState.m_search_source = false;
            }
            // make the new state current now the data fetch is done
			m_CurrentState.CopyContent(newState);

			// status bar
			OnRowSelected(0);
			// update table/view panel
			int row_panel = 1;
			statusBar1.Panels[row_panel].Text = make_status_pane_text(m_Model.DbView);
			// filter?
			//temp disable
			UpdateFilterPanel(m_Model.DbView);
			//setToolbarState();
		}
/*
		private void do_table_search_sync(GridState newState)
		{
			if (!Commit_Changes())
				return;
			GetGridData(newState);
			UpdateGridView(newState);
		}
*/

        private void do_table_search_async(GridState newState)
        {
            if (!Commit_Changes())
                return;

            if (m_CurrentDataThread != null)
            {
                DialogResult res = MessageBox.Show("Data fetch is in progress - do you want to cancel that.",
                                                    "*** Confirm cancel ***",
                                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (res == DialogResult.No)
                    return; // keep going

                if (m_CurrentDataThread != null)
                {
                    m_CurrentDataThread.Cancel();
                    m_CurrentDataThread = null;
                    onFinishAsyncOp();
                    m_NewState.CopyContent(m_CurrentState);
                    return; // they'll have to do it again. This feature is not great
                }
            }
            // Pre-fetch data
            // Get view from display type in state
            DbViewBase vb = null;
            // special if data view 
            if (newState.m_DisplayType == DisplayType.CustomView)
            {
                vb = this.m_vbCustom; // ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
            }
            else
            {
                // keep a map of objects for non-custom views.
                if (!m_Views.ContainsKey(newState.m_DisplayType))
                    this.m_Views.Add(newState.m_DisplayType, getDbView(newState.m_DisplayType));
                vb = this.m_Views[newState.m_DisplayType];
				//if (newState.m_DisplayType == DisplayType.History)
				//{
				//    DbHistory vbh = (DbHistory)vb;
				//    vbh.Refresh(this.m_Navigation.getAllHistory());
				//}
				//if (newState.m_DisplayType == DisplayType.JobSteps &&  // jobsteps
				//    m_CurrentState.m_DisplayType == DisplayType.Jobs)  // clicked on from jobs
				//{
				//    DbUtilJobSteps vbj = (DbUtilJobSteps)vb;
				//    vbj.UpdateJobId();
				//}
				//if (newState.m_DisplayType == DisplayType.Structure)
				//{
				//    DbViewStructure vs = (DbViewStructure)vb;
				//    vs.SetTable(GetTableName());
				//}
            }
            // test for missing items.
            if (vb == null)
                return; // ie. new view
            // get connection info from tag
            connInfo ci = m_Model.ConnectionList[newState.m_connection_tag];
            // and connection string from that
            String connStr = ci.connectionString;
            if (connStr.Length == 0)
                return;

            //
            // Development hack for search source
            //
            if (newState.m_search_source)
                // either because this is illegal reuse of a member or something is wrong in the code.
                newState.m_search_text = m_Model.SourceSearchString;  
            //
            // join the code.
            //
            // this.results.Enabled = false; // not necessary if working is a modal dialog
            WinFormThreading.ThreadProcessState connectionState = new WinFormThreading.ThreadProcessState();
            DataFetchWorker fetchThread = new DataFetchWorker(this, (WinFormThreading.ProgressStateDelegate)DataFetchProgress, connectionState);
            connectionState.UserData = fetchThread;
            // set the params for the action
            // sql
            try
            {
                // fetchThread.Sql = vb.BuildSql(newState.m_search_text);
                fetchThread.View = vb;
                fetchThread.SearchSource = newState.m_search_source;
                fetchThread.SearchText = newState.m_search_text;
                fetchThread.ConnectionString = connStr;
                // connection string we have
                m_CurrentDataThread = fetchThread;
                fetchThread.KickOffThread();

                this.onStartAsyncOp();
                // showWorkingDialog();
                // this.m_CancelWorkForm.ShowDialog(this);
                this.timerConnecting.Interval = 1000; // allow 1s. before flashing
                this.timerConnecting.Start();
            }
            catch (NotImplementedException ex)
            {
                displayExceptionMessage(new DbViewApplicationException(ex.Message), "fetch");
            }
//			m_Threadstate = threadstate.working;
//			this.DataFetcher.RunWorkerAsync(newState);
			
        }
		
		void showWorkingDialog()
		{
			if (!m_WorkingDialogDisplayed)
			{
				m_WorkingDialogDisplayed = true;
				this.m_CancelWorkForm.ShowDialog(this);
			}
		}
		void hideWorkingDialog()
		{
			if (m_WorkingDialogDisplayed)
			{
				m_WorkingDialogDisplayed = false;
				this.m_CancelWorkForm.Close();
			}
		}
/*
		private void DataFetcher_DoWork(object sender, DoWorkEventArgs e)
		{
			try
			{
				GridState newState = (GridState)e.Argument;
				GetGridData(newState);
			}
			catch (DbViewApplicationException ex)
			{
				if (this.m_Threadstate == threadstate.working)
				{
					this.m_Threadstate = threadstate.errored;
					this.displayExceptionMessage(ex, "Fetch data");
					m_NewState.CopyContent(m_CurrentState);
				}
			}
		}

		private void DataFetcher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if (m_Threadstate != threadstate.cancelled ||
				m_Threadstate != threadstate.errored)
			m_Threadstate = threadstate.done;
		}
*/
		private void do_table_search(GridState newState)
		{
			if (!Commit_Changes())
				return;
			// prime the custom view for threading
			//if (newState.m_DisplayType == DisplayType.CustomView)
			//    this.m_vbCustom = ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
			
			// get the state of the grid and set the report params
			do_table_search_async(newState);
		}

		private void timerConnecting_Tick(object sender, EventArgs e)
		{
// below is a bit modal
/*		
			// delayed display
			if (m_CurrentDataThread != null)
				this.showWorkingDialog();
			this.timerConnecting.Stop();
*/
            if (m_CurrentDataThread != null)
            {
			    //	this.m_CancelWorkForm.ShowDialog(this);
                if (this.comboSearchPart.BackColor == System.Drawing.SystemColors.Window)
                    this.comboSearchPart.BackColor = Color.OrangeRed;
                else
                    this.comboSearchPart.BackColor = System.Drawing.SystemColors.Window;
                timerConnecting.Interval = 200; // speed up once it's started
            }
            else
            {
                this.timerConnecting.Stop();
                this.comboSearchPart.BackColor = System.Drawing.SystemColors.Window;
            }
		}
		
		// delegate for the cancel connection window to use.
		void cancelFetch()
		{
			if (m_CurrentDataThread != null)
			{
				m_CurrentDataThread.Cancel();
				m_CurrentDataThread = null;
				m_NewState.CopyContent(m_CurrentState);
			}
			//m_CancelWorkForm.Close();
			hideWorkingDialog();
		}
		
		private void DataFetchProgress(WinFormThreading.ThreadProcessState connectionState)
		{
			DataFetchWorker thread = (DataFetchWorker)connectionState.UserData;
			if (thread == m_CurrentDataThread)
			{
				hideWorkingDialog();
				// restore stuff
				this.onFinishAsyncOp();

				if (connectionState.IsErrored)
				{
					// restore to previous same as when cancelling.
					m_NewState.CopyContent(m_CurrentState);
					MessageBox.Show(this, connectionState.Exception.Message);
				}

				if (connectionState.IsDone)
				{
					// get the dset somehow.
					this.OnFinishFetchData(thread.View, thread.DSet);
				}
				// test again just in case. I know this ain't thread safe.
				if (thread == m_CurrentDataThread)
					m_CurrentDataThread = null;
			}
		}


/*
        private void do_table_search()
        {
            if (!Commit_Changes())
                return;
            Table_Search();
        }
*/
        void onStartAsyncOp()
        {
            this.btnGo.Text = "&Cancel";
        }

        void onFinishAsyncOp()
        {
            this.btnGo.Text = "&Search";
        }



        private void ResetState(GridState g)
        {
            if (g != null)
            {
                // change connection if necessary
                if (g.m_connection_tag !=  this.m_NewState.m_connection_tag)
                {
                    connInfo targetInfo = this.m_Model.ConnectionList[g.m_connection_tag];
                    this.m_Model.ConnectionString = targetInfo.connectionString;

                    // Official from here 
                    SetWindowTitle(g.m_connection_tag);
                    // same for status
                    int server_panel = 0;
                    this.statusBar1.Panels[server_panel].Text = String.Format("{0}.{1}", targetInfo.Server, targetInfo.Database);
                }
                // do the text
                // do the view
				//ModelFormControl.InitialiseViewSelectionCombo(m_Model, this.comboView, m_NewState.m_connection_tag, false);
				//if (g.m_DisplayType > DisplayType.CustomView)
				//{
				//    this.comboView.SelectedIndex = -1;  // no view    
				//    // need to spike the table to prevent crash.
				//    if (g.m_DisplayType == DisplayType.Structure ||
				//       g.m_DisplayType == DisplayType.FieldMetaData
				//    )
				//    {
				//        int idx = g.m_view_name.IndexOf(' ');
				//        String s = g.m_view_name.Remove(0,idx).Trim();
				//        // this.m_SchemaTable = s;
				//    }
				//}                    
				//else                    
				//    ModelFormControl.SetComboSelection(this.comboView, g.m_view_name);
                    
				// simulate user entering this.
				this.comboSearchPart.Text = g.m_search_text;
                // populate the grid
                int iHoldRow =  g.m_grid_row;
                // update the state 
                m_NewState.CopyContent(g);
				changeView(m_NewState);
                // reset the row under certain conditions.
                if (iHoldRow >= this.results.DisplayedRowCount(true)
                && iHoldRow < this.theDset.Tables[0].Rows.Count)
                {
                    this.results.CurrentCell = this.results.Rows[iHoldRow].Cells[0];
                    this.results.Rows[iHoldRow].Selected = true;
                }
                // reset pop-up menus as state change may have switched viwe type
                this.update_popup_menu();
            }
        }

        private void NavigateBack()
        {
            if (!Commit_Changes_with_confirm(false)) //ok
                return;
			// todo: use newstate
            GridState g = this.m_Navigation.back();
            ResetState(g);
        }


		//private void AddNewView(String table_name_in)
		//{
		//    String strSql = String.Format("select name from sysobjects where xtype = 'U' order by name");
		//    DataSet dset;
		//    Helper.GenericMakeDset(m_Model.ConnectionString, strSql, "TABLENAMES", out dset);
		//    DataTable t = dset.Tables[0];
		//    String [] TableNameList = new String[t.Rows.Count];
		//    int pos_of_in_table = 0;
		//    for (int idx = 0; idx < t.Rows.Count; ++idx)
		//    {
		//        TableNameList[idx] = t.Rows[idx][0].ToString();
		//        if (table_name_in == TableNameList[idx])
		//            pos_of_in_table = idx;
		//    }				
		//    bool bCompleted = false;
		//    int  hold_index = -1; // this.comboView.SelectedIndex;
            
		//    using (NewViewForm nvf = new NewViewForm(TableNameList, pos_of_in_table, this.m_Model.ConnectionString))
		//    {
		//        nvf.ShowDialog(this);
		//        if (nvf.DialogResult == DialogResult.OK)
		//        {
		//            // todo: check for duplicate name
		//            ViewParams vp = new ViewParams(m_Model.CheckChangeDuplicateName(nvf.ViewName), nvf.Table);
		//            vp.Connection = m_NewState.m_connection_tag;
		//            if ( nvf.JoinClause.Length > 0)
		//                vp.JoinClause =  nvf.JoinClause;
		//            ViewEditForm dlgEdViewinfo = new ViewEditForm(m_Model, vp);
		//            dlgEdViewinfo.ShowDialog(this);
		//            if (dlgEdViewinfo.DialogResult == DialogResult.OK)
		//            {
		//                // update model
		//                DbConfigurableView newview = new DbConfigurableView(vp, this);
		//                m_Model.DbViewCollection.Add(newview);
		//                // link it to to the current connection
		//                create_link(newview.Title);
		//                // persist the view to file
		//                m_Model.SaveViewInfo();
		//                // update the selection combo box
		//                // ModelFormControl.InitialiseViewSelectionCombo(m_Model, this.comboView, m_NewState.m_connection_tag, true);
		//                // activate the view
		//                m_NewState.m_DisplayType = DisplayType.CustomView;
		//                this.changeView(m_NewState);
		//                bCompleted = true;
		//            }	
		//        }
		//        //if (!bCompleted)
		//        //    this.comboView.SelectedIndex = hold_index;
		//    }
		//}

//        private void AdhocView(String table_name_in, String filterClause)
//        {
//            // update model
//            ViewParams vp = new ViewParams(table_name_in, table_name_in);
//            vp.Connection = m_NewState.m_connection_tag;
//            vp.IsPermanent = false; // will disappear on next view creation
//            vp.FilterClause = filterClause;

//            // set auto-filter here
//            int iTextFieldCount = 3;  // set 1st three text fields
//            int iNumberFieldCount = 3;  // auto-set numbers in the first three fields
//            DataSet dset;
//            Helper.GetStructure(m_Model.ConnectionString, vp.Table, out dset);
//            int iTypeIndex = 2;      // index of field type in schema dset

//            for (int iRowIndex = 0; iRowIndex < dset.Tables[0].Rows.Count & iTextFieldCount > 0; ++iRowIndex)
//            {
//                String strColumnName = (String)dset.Tables[0].Rows[iRowIndex][0];
//                System.Type s = (System.Type)dset.Tables[0].Rows[iRowIndex][iTypeIndex];
//                if (s == typeof(String))
//                {
//                    vp.AddTextFilterColumn(strColumnName);
//                    --iTextFieldCount;
//                }
//                // do the same for numbers - just the first few
//                if (iRowIndex < iNumberFieldCount)
//                    if (s == typeof(int))
//                        vp.AddNumberSearchColumn(strColumnName);

//            }
//            // end set auto-filter here
//            //////////
//            connInfo targetInfo = GetConnectionInfo();
//            // check whether the view is attached to the current connection
//            if (vp.Connection == targetInfo.Name)
//            // if (!m_Model.View_LInker.is_linked(targetInfo.Name, vp.DisplayName))
//            {
//                // if view does not exist at all then create it
//                //if (!m_Model.ViewExists(vp, targetInfo.Name))
//                //{
//                //    vp.Name = m_Model.CheckChangeDuplicateName(vp.Name);
//                //    DbConfigurableView newview = new DbConfigurableView(vp, this);
//                //    m_Model.DbViewCollection.Insert(0, newview); // add at top
//                    // reset drop down.
////					ModelFormControl.InitialiseViewSelectionComboEx(m_Model, this.comboView, m_NewState.m_connection_tag, ModelFormControl.VCInit.start);
//            //	}
//                // if view exists just link it for the current connection
//                else
//                {
//                    // must set the selected index to the item that matches
////					ModelFormControl.SetComboSelection(comboView, vp.DisplayName);
//                    // update the filter in the model - drilling from an aggregate report
//                    if (filterClause.Length > 0)
//                    {
//                        //DbViewBase selected = ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
//                        //DbConfigurableView view = (DbConfigurableView)selected;
//                        //view.ViewParams.FilterClause = filterClause;
//                    }
//                }
//            }
//            else
//            {
//            }
//            // change the view and refresh the grid
//            this.m_NewState.m_DisplayType = DisplayType.CustomView;
//            changeView(m_NewState);
//        }
		
		/*
		private void AdhocView(String table_name_in, String filterClause)
		{
			// update model
			ViewParams vp = new ViewParams(table_name_in, table_name_in);
			vp.Connection = m_NewState.m_connection_tag;
			vp.IsPermanent = false; // will disappear on next view creation
			vp.FilterClause = filterClause;

			// set auto-filter here
			int iTextFieldCount = 3;  // set 1st three text fields
			int iNumberFieldCount = 3;  // auto-set numbers in the first three fields
			DataSet dset;
			Helper.GetStructure(m_Model.ConnectionString, vp.Table, out dset);
			int iTypeIndex = 2;      // index of field type in schema dset

			for (int iRowIndex = 0; iRowIndex < dset.Tables[0].Rows.Count & iTextFieldCount > 0; ++iRowIndex)
			{
				String strColumnName = (String)dset.Tables[0].Rows[iRowIndex][0];
				System.Type s = (System.Type)dset.Tables[0].Rows[iRowIndex][iTypeIndex];
				if (s == typeof(String))
				{
					vp.AddTextFilterColumn(strColumnName);
					--iTextFieldCount;
				}
				// do the same for numbers - just the first few
				if (iRowIndex < iNumberFieldCount)
					if (s == typeof(int))
						vp.AddNumberSearchColumn(strColumnName);
        
			}
			// end set auto-filter here
			//////////
			connInfo targetInfo = GetConnectionInfo();
			// check whether the view is attached to the current connection
			if (vp.Connection == targetInfo.Name)
			// if (!m_Model.View_LInker.is_linked(targetInfo.Name, vp.DisplayName))
			{
				// if view does not exist at all then create it
				if (!m_Model.ViewExists(vp))
				{
					vp.Name = m_Model.CheckChangeDuplicateName(vp.Name);
					DbConfigurableView newview = new DbConfigurableView(vp, this);
	//                m_Model.DbViewCollection.Add(newview);
					m_Model.DbViewCollection.Insert(0, newview); // add at top
					// link it to to the current connection
					// below is old
					// create_link(newview.Title);
				}
				// if view exists just link it for the current connection
				else
				{
					// below is old
					//create_link(vp.DisplayName);
				}
				// reset drop down.
				ModelFormControl.InitialiseViewSelectionComboEx(m_Model, this.comboView, m_NewState.m_connection_tag, ModelFormControl.VCInit.start);
			}
			else
			{
				// must set the selected index to the item that matches
				ModelFormControl.SetComboSelection(comboView, vp.DisplayName);
			}
			// change the view and refresh the grid
			this.m_NewState.m_DisplayType = DisplayType.CustomView;
			changeView(m_NewState);
		}
		*/
 /*
        private void changeView_Old()
        {
            try 
            {
                // reset the view object in the model
                ResetView();

                // need dirty flag modifier
                // get search text associated with view
    // disable auto view 
    // this.comboSearchPart.Text = this.get_search_text();
                // if the search text was used in the last search then discard it.
                if (this.comboSearchPart.Text == this.m_strLastSearchTextUsed)
                    this.comboSearchPart.Text = "";

                // ** above is new
                Table_Search();
                // reset pop-up menus as view change may require different choices
                this.update_popup_menu();
            }
            catch (DbViewApplicationException exc)
            {
                this.displayExceptionMessage(exc, "Change view");
            }
        }
*/
		private void changeView(GridState newState)
		{
			try
			{
				// the relationship between this.comboSearchPart.Text and newState.m_search_text
				// if they are different prefer comboSearchPart.Text
				// to cover the case where text is entered in to the search box and view is
				// change from the toolbar or the menu
				// 
				// test whether to implement last search/clear search logic
				if (comboSearchPart.Text == this.m_strLastSearchTextUsed &&
				    newState.m_search_text == this.m_strLastSearchTextUsed)
					newState.m_search_text = "";
				else
					newState.m_search_text = comboSearchPart.Text;
				// ** above is new
				do_table_search(newState);
				// reset pop-up menus as view change may require different choices
				this.update_popup_menu();
			}
			catch (DbViewApplicationException exc)
			{
				this.displayExceptionMessage(exc, "Change view");
			}
		}

		//private void updateFavourites()
		//{
		//    // remove old
		//    int staticCount = 3; // add to favourites and separator
		//    while (this.menuFavourites.MenuItems.Count > staticCount)
		//        this.menuFavourites.MenuItems.Remove(this.menuFavourites.MenuItems[staticCount]);

		//    String connName = m_NewState.m_connection_tag;
		//    ArrayList favs;
		//    this.m_Model.FavouriteManager.getFavourites(connName, out favs);
		//    foreach (Favourite fav in favs)
		//    {
		//        MenuItem mi = new MenuItem(fav.ToString(), favourite_Click);
		//        this.menuFavourites.MenuItems.Add(mi);
		//    }
		//}

		//private bool SetFilter(String table, String field, String value)
		//{
		//    if (!Commit_Changes_with_confirm(false)) //ok
		//        return false;

		//    int iViewIndex = -1; //this.comboView.SelectedIndex;
		//    if (iViewIndex == -1)
		//        return false;
		//    try
		//    {
		//        DbConfigurableView view = (DbConfigurableView)this.m_Model.DbView;
		//        if (table.Length > 0)
		//        {
		//            // Not a field picker form
		//            using (ViewFilterForm form = new ViewFilterForm(this.m_Model, table, field, value, view.ViewParams.FilterClause))
		//            {
		//                form.ShowDialog(this); //modal mode
		//                if (form.DialogResult == DialogResult.OK)
		//                {
		//                    String hold = view.ViewParams.FilterClause;
		//                    // add in the form here.
		//                    view.ViewParams.FilterClause = form.Clause;
		//                    // 
		//                    try
		//                    {
		//                        m_NewState.m_DisplayType = DisplayType.CustomView;
		//                        this.do_table_search(m_NewState);
		//                    }
		//                    catch (DbViewApplicationException ex)
		//                    {
		//                        this.displayExceptionMessage(ex, "Probable bad filter clause");
		//                        view.ViewParams.FilterClause = hold;
		//                        this.do_table_search(m_NewState);
		//                    }
		//                }
		//            }
		//        }
		//    }
		//    catch (System.InvalidCastException exc)
		//    {
		//        MessageBox.Show(this, "Cannot filter this view");
		//        return false;
		//    }
		//    return true;
		//}
        


        private void SetMenuState()
        {
            //DbUtilBase ut = m_Model.DbUtil;
            //miEdit.Enabled =       ut.IsEdit;
        }

		//private void actionFindInSource(DisplayType ViewOrProcType)
		//{
		//    // get current row
		//    int iViewIndex = this.comboView.SelectedIndex;
		//    // obtain the table name for a suggestion
		//    String table_name = "";
		//    // todo: need to modify this test.
		//    if (iViewIndex == -1)
		//    {
		//        // only if on the table view 
		//        // use the currently selected cell row to obtain the table name 
		//        DataRow row;                
		//        int iRowIndex = this.getSelectedRow(out row);
		//        table_name = row[0].ToString();
		//        // search source.
		//        // set flag in controller class
		//        // new
		//        SearchSource2(table_name, SourceSearchForm.searchTarget.Undetermined);
		//    }
		//}

		//private void SearchSource2(String searchText, SourceSearchForm.searchTarget tgtIn)
		//{
		//   using (SourceSearchForm f = new SourceSearchForm(tgtIn))
		//   {
		//        f.SearchText = searchText;
		//        DialogResult res = f.ShowDialog(this);
		//        if (res == DialogResult.OK)
		//        {
		//            DisplayType tgtViewType = (f.SourceSearchTarget == SourceSearchForm.searchTarget.Views) ? DisplayType.Views :
		//            (f.SourceSearchTarget == SourceSearchForm.searchTarget.Procs) ? DisplayType.Procs :
		//            (f.SourceSearchTarget == SourceSearchForm.searchTarget.Funcs) ? DisplayType.Functions :
		//            (f.SourceSearchTarget == SourceSearchForm.searchTarget.Tables) ? DisplayType.Tables :
		//            (f.SourceSearchTarget == SourceSearchForm.searchTarget.Calcs) ? DisplayType.Calculated :
		//            (f.SourceSearchTarget == SourceSearchForm.searchTarget.JobSteps) ? DisplayType.JobSteps :
		//                                                                        DisplayType.Procs;
		//            m_Model.SourceSearchString = f.SearchText;
		//            m_NewState.m_search_source = true;
		//            m_NewState.m_search_text = f.SearchText;
		//            m_NewState.m_DisplayType = tgtViewType;
		//            this.changeView(m_NewState);

		//        }
		//    }
		//}

		//private void actionFindInSource2()
		//{
		//    // get current row
		//    int iViewIndex = this.comboView.SelectedIndex;
		//    // obtain the table name for a suggestion
		//    String table_name = "";
		//    // todo: need to modify this test.
		//    if (iViewIndex == -1)
		//    {
		//        // only if on the table view 
		//        // use the currently selected cell row to obtain the table name 
		//        DataRow row;
		//        int iRowIndex = this.getSelectedRow(out row);
		//        table_name = row[0].ToString();
		//        // search source.
		//        // set flag in controller class
		//        this.comboView.SelectedIndex = -1;  // no view
		//        // pass into search form 
		//    }
		//}
        
		//// make public for right-click functionality
		//public void showDependenciesFor(String objectName)
		//{
		//   // set flag in controller class
		//    m_NewState.m_DisplayType = DisplayType.Dependencies;
		//    try
		//    {
		//        m_NewState.m_search_text = objectName;
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Dependencies");
		//    }
            
		//}
        
//        private void RowsetRefresh(bool auto)
//        {
//            connInfo ci = GetConnectionInfo();
//            String connName = m_NewState.m_connection_tag;
//            if (auto == true)
//            {
//                String message = "";
//                // check auto conditions
//                // target is dev
//                if (ci.Name.ToUpper().Substring(0,3) != "DEV")
//                    message = "Auto refresh only available for dev databases";
//                if (message.Length > 0)
//                {
//                    MessageBox.Show(message, "Cannot perform Auto", MessageBoxButtons.OK, MessageBoxIcon.Information);
//                    auto = false; // switch to manual
//                }
//            }
//            String sourceDb = lastCopyTgtConn;
//            // get table from selected row
//            DataRow sr1;
//            this.getSelectedRow(out sr1);
//            String targetTable = sr1[0].ToString();
//            if (auto == false || lastCopyConn != connName) // 2nd is auto-refresh that requires a connection
//            {
//                // confirm selection and select the source connection for the refresh
//                using (RefreshTableForm Dlg = new RefreshTableForm(m_Model))
//                {
//                    Dlg.TargetDb = ci.Name;
//                    Dlg.SourceDb = ci.Name;
//                    Dlg.SourceTable = targetTable;
//                    // for multiple table copy operations
//                    // if there is no change of connection since last op 
//                    // ie. will also fail check if no last op
//                    if (lastCopyConn == connName)
//                    {
//                        Dlg.SourceDb = lastCopyTgtConn;
//                    }
//                    DialogResult res = Dlg.ShowDialog(this);
//                    if (res == DialogResult.Cancel)
//                        return;
//                    sourceDb = Dlg.SourceDb;
//                }
//            }
//            String sourceTable = targetTable;

//            // Check they have the correct schema.
//            TableSchema targetSchema = new TableSchema(m_Model, targetTable);
//            targetSchema.Populate();
//            // but first check whether there is a pkey
//            FieldInfo[] Pkeys = targetSchema.PKeyFields;
//            if (Pkeys.Length == 0)
//            {
//                MessageBox.Show(String.Format("Table {0} requires a primary key for this to work", targetTable), "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
//                return;
//            }

//            lastCopyConn = connName;
//            lastCopyTgtConn = sourceDb; // ooops.

//            // TODO: add validation of source.
//            ScriptingHelper helper = new ScriptingHelper(sourceTable, targetTable, targetSchema);
//            // get connection for source from the dialog object
//            ci = m_Model.ConnectionList[sourceDb];
//            // generate the script
//            String script = helper.ScriptRowsetRefresh(ci);
//            if (auto == false)
//            {
//                // display
//                SourceForm2 f = new SourceForm2(targetTable, script, "");
//                f.Show();
//            }
//            else
//            {
//                DataSet dset;
//                script += "\nSELECT @@VERSION";
//                this.Cursor = Cursors.WaitCursor;
//                Helper.GenericMakeDset(m_Model.ConnectionString, script, "TABLENAMES", out dset);
//                this.Cursor = this.DefaultCursor;
//                MessageBox.Show(String.Format("{0} has been AutoRefreshed from {1}", targetTable, sourceDb));
//            }
//        }

//        private void ShowDependencies_Click(object sender, EventArgs e)
//        {
//            DataRow row;
//            Helper.getSelectedRow(this.results, out row);
//            String objectName = row[0].ToString();

//            showDependenciesFor(String.Format("^{0}$", objectName));
//        }

        private void action_Profile(object sender, System.EventArgs e, bool bShowAll)
        {
            // get current row
            int iViewIndex = -1; //this.comboView.SelectedIndex;
            // todo: need to modify this test.
            // only if on the table view 
            //DataGridViewCell ds = results.CurrentCell;
            // use the currently selected cell row to obtain the data row to profile 
            //DataRow row = theDset.Tables[0].Rows[ds.RowIndex];
            DataRow row;
            int rowNum = this.getSelectedRow(out row);
            for (int idx = 0; idx < this.theDset.Tables[0].Rows.Count; ++idx)
            {
            }
            // create 
//            m_Profile = new DbProfile(this.m_Model, this.results, this.theDset.Tables[0], ds.RowIndex, bShowAll);
//            this.UpdateViewCache(DisplayType.Profile, new DbProfile(this.m_Model, this.results, this.theDset.Tables[0], rowNum, bShowAll));
            m_NewState.m_DisplayType = DisplayType.Profile;
            this.changeView(m_NewState);
        }

//        private void action_GotoState(object sender, System.EventArgs e)
//        {
//            // get current row
//            int iViewIndex = this.comboView.SelectedIndex;
//            // use the currently selected cell row to obtain the data row to profile 
//            DataRow row;
//            //DataRow row = theDset.Tables[0].Rows[ds.RowIndex];
//            this.getSelectedRow(out row);
//            // create 
//            int iSeq = (int)row[0]; // column is id 
//            // get state. 
//            GridState g = this.m_Navigation.History.findInList(iSeq);
//            ResetState(g);
//        }

//        private void actionAggregate(int aggType)
//        {
//            try
//            {
//                String table, field;
//                DataRow row;
//                DataGridViewCell ds = results.CurrentCell;
//                table = theDset.Tables[0].TableName;
//                field = theDset.Tables[0].Columns[ds.ColumnIndex].Caption;
//                System.Type fieldType = theDset.Tables[0].Columns[ds.ColumnIndex].DataType;
//                // get where clause
//                ViewParams vp = m_Model.DbView.ViewParams;
//                m_Views[DisplayType.Aggregate] = new DbViewAggregate(this.m_Model, vp, field, fieldType, aggType);
//                m_NewState.m_DisplayType = DisplayType.Aggregate;
//                changeView(m_NewState);
///*
//                // set flag in controller class
//                this.comboView.SelectedIndex = -1;  // no view
//                m_DisplayType = DisplayType.Aggregate;
//                this.changeView();
//*/
//            }
//            catch (DbViewApplicationException ex)
//            {
//                this.displayExceptionMessage(ex, "Aggregation");
//            }
//       }

		//private void LaunchNewInstance()
		//{
		//    Process p = null;
		//    try
		//    {
		//        // more shameless hacking from code project
		//        string targetDir;
		//        targetDir = Application.ExecutablePath;
		//        p = new Process();
		//        p.StartInfo.WorkingDirectory = targetDir;
		//        p.StartInfo.FileName = Application.ExecutablePath;
		//        // use current connection
		//        String arg1 = m_NewState.m_connection_tag;
		//        p.StartInfo.Arguments = String.Format("\"{0}\"", arg1);
		//        p.StartInfo.CreateNoWindow = false;
		//        p.Start();
		//    }
		//    catch (SystemException ex)
		//    {
		//        throw new DbViewApplicationException("Could not launch new instance", ex);
		//    }
		//}       
       
		///// <summary>
        /// This is WIP very specialist method for viewing DC messages. Past it's time now I think.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <param name="bShowAll"></param>
 
        #endregion
        
        #region specific event logic
        
/*
        // revised 15/11
        // commit. set up state for new connection
        // on success update gui
        private void OnChangeConnection_Old(String new_conn_tag)
        {
            if (!Commit_Changes_with_confirm(true)) // ok
                return;
            try
            {
                // this needs old details
                // what if it throws an exception - should be moved out.
                // make new detaild
                connInfo targetInfo = this.m_Model.ConnectionList[new_conn_tag];
                this.m_Model.ConnectionString = targetInfo.connectionString;

				// really need to do this following a successful launch
				// Official from here 
                SetWindowTitle(new_conn_tag);
                // same for status
                int server_panel = 0;
                this.statusBar1.Panels[server_panel].Text = String.Format("{0}.{1}", targetInfo.Server, targetInfo.Database);
                // status bar
                UpdateStatusBar(targetInfo);
                // mru
                mruMenu.AddFile((String)targetInfo.Name, (String)targetInfo.Name);
                // views
                ModelFormControl.InitialiseViewSelectionCombo(m_Model, this.comboView, m_NewState.m_connection_tag, false);
                // favourites
                this.updateFavourites();
                // grid.
                // Nb: always anchor on tables view on change of connection
                m_DisplayType = DisplayType.Tables;   // make tables
                this.comboView.SelectedIndex = -1;         // reset view combo
                // set the view
                ResetView();
                // clear search text
                if (this.comboSearchPart.Text == this.m_strLastSearchTextUsed)
                    this.comboSearchPart.Text = "";
                // 
                Table_Search(); 
                // reset pop-up menus as view change may require different choices
                this.update_popup_menu();
            }
            catch (DbViewApplicationException ex)
            {
                displayExceptionMessage(ex, "Connection");
            }
        }
*/
		// commit. set up state for new connection
		// on success update gui
		private void OnChangeConnection(String new_conn_tag)
		{
			if (!Commit_Changes_with_confirm(true)) // ok
				return;
			try
			{
/*
				// bootstrap test. Set current connection from new if current is empty
				// Not sure that this is the correct place
				if (m_CurrentState.m_connection_tag.Length == 0)
					m_CurrentState.m_connection_tag = new_conn_tag;
*/
				// set new connection
				m_NewState.m_connection_tag = new_conn_tag;
				// show tables when you change connection
				m_NewState.m_DisplayType = DisplayType.Tables;
				// clear search text as we want to see all tables
				m_NewState.m_search_text = "";
				// populate the grid now
				do_table_search(m_NewState);
			}
			catch (DbViewApplicationException ex)
			{
				displayExceptionMessage(ex, "Connection");
			}
		} 

		private void OnConnected()
		{
			// reset pop-up menus as view change may require different choices
			this.update_popup_menu();

			// this needs old details
			// what if it throws an exception - should be moved out.
			// make new detail
			connInfo targetInfo = this.m_Model.ConnectionList[m_NewState.m_connection_tag];
			// really need to do this following a successful launch
			// Official from here 
			this.m_Model.ConnectionString = targetInfo.connectionString;
			SetWindowTitle(m_NewState.m_connection_tag);
			// same for status
			int server_panel = 0;
			this.statusBar1.Panels[server_panel].Text = String.Format("{0}.{1}", targetInfo.Server, targetInfo.Database);
			// status bar
			UpdateStatusBar(targetInfo);
			// mru
			mruMenu.AddFile((String)targetInfo.Name, (String)targetInfo.Name);
			// views
			//ModelFormControl.InitialiseViewSelectionCombo(m_Model, this.comboView, m_NewState.m_connection_tag, false);
			// favourites
			//this.updateFavourites();
			//// grid.
			//// Nb: always anchor on tables view on change of connection
			//// not wanted.
			//// m_DisplayType = DisplayType.Tables;   // make tables
			//this.comboView.SelectedIndex = -1;         // reset view combo
		}


        private void OnMenuFileMru(int number, String filename)
        {
            // 
            if (false)
            {
                MessageBox.Show(String.Format("{0} not found", filename));
                mruMenu.RemoveFile(number);
            }
            else    
            {
                mruMenu.SetFirstFile(number);
                OnChangeConnection(filename); // delegate to main function
            }
        }
       
        private void OnClose(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!Commit_Changes_with_confirm(true)) // ok
            {
                // here if there is an error with the save or 
                // the user cancels.
                e.Cancel = true;    // prevent close.
                return;
            }
            mruMenu.SaveToRegistry();		
        }

        private void on_save_new_view(DbViewBase db, ViewParams vp)
        {
			//create_link(vp.DisplayName);
			//m_Model.SaveViewInfo();
			//db.Title = vp.DisplayName;
			//ModelFormControl.InitialiseViewSelectionCombo(m_Model, this.comboView, m_NewState.m_connection_tag, false);
			//this.m_NewState.m_DisplayType = DisplayType.CustomView; // set to view index
			//changeView(m_NewState);
        }
        private void OnRowSelected(int Row)
        {
            int row_panel = 2;
            if (Row < 0 || Row >= theDset.Tables[0].Rows.Count)
            {
                statusBar1.Panels[row_panel].Text = String.Format("{0}", theDset.Tables[0].Rows.Count);
                return;
            }
            statusBar1.Panels[row_panel].Text = String.Format("{0}/{1}", Row + 1, theDset.Tables[0].Rows.Count);
            // 
            // get data for status from row
            //
			//// use up to date version
			//if (this.m_CurrentState.m_DisplayType == DisplayType.Tables)
			//{
			//    if (this.FieldPanel.Visible)
			//    {
			//        String table_name = this.GetTableName();
			//        OnOpenFieldPicker(table_name);
			//    }
			//}
            
		}
        #endregion

        #region event handlers
        // control handlers
        private void MainForm_Load(object sender, System.EventArgs e)
        {
            this.Show();
//            if (this.m_StartupConnectionTag.Length > 0)
            if (this.m_NewState.m_connection_tag.Length > 0)
            {
				OnChangeConnection(this.m_NewState.m_connection_tag);
                m_StartupConnectionTag = ""; // just in case; this is a use-once concept
            }                
            else
                this.fileConnect_Click(sender, e);
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Saves any changes made to view 
            // not necessary and causes problems.
            //m_Model.SaveViewInfo();
        }
        private void MainForm_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            int i = (int)e.Action;
            // set flag here and offer save/changes option?
            this.m_ViewDirty = true; // set a dirty flag
        }
		//private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		//{
		//    switch(e.Button.ImageIndex)
		//    {
		//        case 0: this.actionNavigateBack_Click(sender, e); break;
		//        case 1: this.showHistory_Click(sender, e); break;
		//        case 2: this.fileConnect_Click(sender, e); break;
		//        case 3: this.actionClearSearchEx_Click(sender, e); break;
		//        case 4: this.schemaTables_Click(sender, e); break;
		//        case 5: this.schemaViews_Click(sender, e); break;
		//        case 6: this.schemaProcs_Click(sender, e); break;
		//        case 7: this.dataChangeView_Click(sender, e); break;
		//        case 8: this.actionFilter_Click(sender, e); break;
		//        case 9: this.actionAggregated_Click(sender, e); break;
		//        case 10: this.menuAggCount_Click(sender, e); break;
		//        case 11: this.actionSearchSource_Click(sender, e); break;
		//        //case 12: this.LaunchNewInstance(); break;
		//        //case 13: this.toolsFieldSelector_Toggle(); break;
		//        /*
		//                        case 1: this.actionNavigateBack_Click(sender, e); break;
		//                        case 2: this.schemaTables_Click(sender, e); break;
		//                        case 3: this.schemaViews_Click(sender, e); break;
		//                        case 4: this.schemaProcs_Click(sender, e); break;
		//                        case 5: this.fileManageConnections_Click(sender, e); break;
		//                        case 6: this.actionNavigateForwards_Click(sender, e); break;
		//                        case 7: this.dataChangeView_Click(sender, e); break;
		//                        case 8: this.dataAddView_Click(sender, e); break;
		//                        case 9: this.fileConnect_Click(sender, e); break;
		//        //                case 10: this.actionClearSearch_Click(sender, e); break;
		//                        case 10: this.actionClearSearchEx_Click(sender, e); break;
		//                        case 14: this.actionNavigateForwards_Click(sender, e); break;
		//                        case 15: this.showHistory_Click(sender, e); break;
		//                        case 16: this.showPermissions_Click(sender, e); break;
		//                        case 19: this.actionSearchSource_Click(sender, e); break;
		//                        case 18: this.schemaFuncs_Click(sender, e); break;
		//                        case 21: this.actionAggregated_Click(sender, e); break;
		//                        case 22: this.actionFilter_Click(sender, e); break;
		//        */
		//    }
		//}
        private void Go_Click(object sender, System.EventArgs e)
        {
            try
            {
                // the go button
                // reset search text
                m_NewState.m_search_text = this.comboSearchPart.Text;
                this.do_table_search(m_NewState);
            }
            catch (DbViewApplicationException ex)
            {
                this.displayExceptionMessage(ex, "Fetch data");
            }
        }

        private void results_ControlAdded(object sender, ControlEventArgs e)
        {
            // once per column? or Column header plus column data
            // Console.WriteLine("{0}", e.ToString());
/* to prevent the control gaining focus if read only
            e.Control.Click += new System.EventHandler(this.DataGridView1_DoubleClick); 
            e.Control.DoubleClick += new 
                System.EventHandler(this.DataGridView1_DoubleClick); 
*/
            // Intercept keypress for controls in grid
            e.Control.KeyDown += new KeyEventHandler(Control_KeyDown);
        }

        // For key presses intercepted from grid controls
        private void Control_KeyDown(object sender, KeyEventArgs e)
        {
            // test whether in edit mode. Leave the method if it is.
            if (!this.m_Model.DbView.IsReadOnly)
                return;

            // check for control keys
            if (e.Alt || e.Control)
                return;
                
            // test keypress range 0-z
            if (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.Z)
            {
                // Move to search box
                comboSearchPart.Focus();
                // Set the key pressed in the box
                comboSearchPart.Text = e.KeyCode.ToString();
                // Set the edit position to after the key just pressed.
                comboSearchPart.Select(1,1);
            }
        }

        // For key presses intercepted from grid controls
        private void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            // check for control keys
            if (e.Control)
				if (e.KeyCode == Keys.C)
				{
					MessageBox.Show("Ouch");
				}
        }


        private void results_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {

            DataGridView myGrid = (DataGridView) sender;
            System.Windows.Forms.DataGridView.HitTestInfo hti;
            hti = myGrid.HitTest(e.X, e.Y);
            if (hti.Type == DataGridViewHitTestType.RowHeader)
            {
                OnRowSelected(hti.RowIndex);
                if (e.Button == MouseButtons.Right)
                {
                    // Set the current cell to cell1, row 1.
                    if (myGrid.CurrentRow.Index != hti.RowIndex)
                        myGrid.CurrentCell = myGrid.Rows[hti.RowIndex].Cells[0];
					this.thePopup.Show(results, new Point(e.X, e.Y));
                }                    
            }
            if (hti.Type == DataGridViewHitTestType.Cell)
            {
                if (e.Button == MouseButtons.Right)
                {
                    if (myGrid.CurrentRow.Index != hti.RowIndex)
                        myGrid.CurrentCell = myGrid.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
                    DataRow dr;
                    Helper.getSelectedRow(results, out dr);
                    
                    String data = dr[hti.ColumnIndex].ToString().Trim();
                    // just copy to clipboard for me
					Clipboard.SetText(data);

                    if (data.Length > 50)
                    {
                        // ready for action. ie Xml pop-up
                    }
                    // if cell contents are lo
                    
                }
            }
			if (e.Button == System.Windows.Forms.MouseButtons.Right)
				if (hti.Type == DataGridViewHitTestType.ColumnHeader)
				{
					TableView.MakeColumnPopup(hti.ColumnIndex, AddColumn_Click, AddColumn_Click).Show(myGrid, new Point(e.X, e.Y));
				}
        }

		private void AddColumn_Click(object sender, System.EventArgs e)
		{
			MenuItem mi = sender as MenuItem;
			// get column code
			String data = mi.Tag.ToString();
			String code = data.Substring(0,1);
			String pos = data.Substring(1);
			int idx;
			int.TryParse(pos, out idx);
			results.Columns[idx].Tag = code;
			// find column to insert before
			// set it up

			this.do_table_search(m_NewState);
		}
 
        private void results_CurrentCellChanged(object sender, System.EventArgs e)
        {
            DataGridView myGrid = (DataGridView)sender;
            // Get the co-ordinates of the focussed cell.
            // TODO
            if (myGrid.CurrentCell != null)
            {
                OnRowSelected(myGrid.CurrentCell.RowIndex);
/*
				// use up to date version
				if (this.m_DisplayType == DisplayType.Tables)
				{
					if (this.FieldPanel.Visible)
					{
						String table_name = this.GetTableName();
						OnOpenFieldPicker(table_name);
					}
				}
*/				
            }
        }

        private void searchPart_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (!Commit_Changes_with_confirm(true)) //ok
                    return;
                this.do_table_search(m_NewState);
            }
        }

        private void comboView_SelectedIndexChanged(object sender, System.EventArgs e)
        {
/*
            this.begin_action();            
            if (this.comboView.SelectedIndex >= 0) // valid view
                this.m_DisplayType = 0;     // clear special to use the view
            changeView();
            this.end_action();            
 */
        }

		//private void comboView_SelectionChangeCommitted(object sender, System.EventArgs e)
		//{
		//    if (this.comboView.DroppedDown == false) // prevents accidental change of view
		//        this.comboView.DroppedDown = true;   // pops the selection instead.
		//    else
		//    {    
		//        if (this.comboView.SelectedIndex >= 0) // valid view
		//        {
		//            DbViewBase selected = ModelFormControl.ViewObjectFromCombo(m_Model, comboView);
		//            if (selected != null)
		//            {
		//                this.m_NewState.m_DisplayType = DisplayType.CustomView;     // clear special to use the view
		//                // update MRU list here 
		//                ModelFormControl.UpdateMruCombo(this.comboView);
		//                // update the view
		//                m_Model.DbViewCollection.Remove(selected);
		//                m_Model.DbViewCollection.Insert(0, selected);
		//                // save to disk to avoid clashed during closedown save
		//                m_Model.SaveViewInfo();
		//            }
		//            else
		//            {
		//                MessageBox.Show("Something is wrong with the selected view", "Can't access view details",
		//                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
		//            }
		//            changeView(m_NewState);
		//        }
		//    }
		//}

        private void searchPart_OnFocus(object sender, System.EventArgs e)
        {
            // when the search edit box gains focus it highlights the current text
            this.comboSearchPart.SelectAll();
        }

  
        private void results_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DataGridView myGrid = (DataGridView) sender;
            System.Windows.Forms.DataGridView.HitTestInfo hti;
            hti = myGrid.HitTest(e.X, e.Y);
            switch (hti.Type)
            {
				case DataGridViewHitTestType.RowHeader:
					results_DoubleClick(sender, e); // this performs the default right-click menu option
					return;
			
				case DataGridViewHitTestType.Cell:
					DbViewBase vb = this.m_Model.DbView;
					if (vb.IsReadOnly)
						results_DoubleClick(sender, e); // this performs the default right-click menu option
					return;

				case DataGridViewHitTestType.ColumnHeader:
		            if (m_CurrentState.m_DisplayType == DisplayType.CustomView)
						this.dataChangeView_Click(sender, e);
					return;
				// anywhere else: nothing
			}
        }

        private void results_DoubleClick(object sender, System.EventArgs e)
        {
            // assume forwarded to logic handles this  this.begin_action();           
            // find default
            int iClickItem = -1;  // default do nothing
            // hunt for default item in context
            for (int idx = 0; idx < this.results.ContextMenu.MenuItems.Count; ++idx)
                if (this.results.ContextMenu.MenuItems[idx].DefaultItem == true)
                    iClickItem = idx;
            // no default item (sloppy or no items)
            if (iClickItem == -1)                    
                if (this.results.ContextMenu.MenuItems.Count > 0)
                    iClickItem = 0; // assume 1st item if there is one
            // if a valid index then invoke the item.
            if (iClickItem >= 0)                    
                this.results.ContextMenu.MenuItems[iClickItem].PerformClick();                  
            // this.end_action();            
        }

         private void menuHistory_Item_Click(object sender, System.EventArgs e)
        {
            MenuItem m = (MenuItem)sender;
            String strText = m.Text;
            GridState g = this.m_Navigation.goBackTo(m.Text);            
            if (g != null)
                ResetState(g);
        }

        private void menuHistory_Popup(object sender, System.EventArgs e)
        {
			//this.menuHistory.MenuItems.Clear();                  
			//String [] astrMemo = this.m_Navigation.getHistoryMemoList();
			//// for each item in the history list
			//foreach (String s in astrMemo)
			//{   
			//    // add menu item.
			//    MenuItem m = new MenuItem(s, new System.EventHandler(this.menuHistory_Item_Click));
			//    this.menuHistory.MenuItems.Add(m);                  
			//}
        }
		
		//// agggregate the items in the selected column
		//private void aggregate_Popup(object sender, System.EventArgs e)
		//{
		//    // current view. Should be a table data content view
		//    // ie. is a table of values and counts following an aggregate command
		//    DbViewBase vb = this.m_Model.DbView;
		//    String table = vb.ViewParams.Table;
		//    //DataRow row;
		//    // Get current cell
		//    DataGridViewCell ds = results.CurrentCell;
		//    // from this get the field to search from the column name and the value from the row data
		//    String field = theDset.Tables[0].Columns[0].Caption; // data is column 0 count is col 1
		//    String value = theDset.Tables[0].Rows[ds.RowIndex][0].ToString();
		//    // create a filter
		//    // check for expanding the null case
		//    String filterClause = String.Format("{0} is NULL", field);
		//    // normally its the non-null case we're after
		//    if (value.Length > 0)
		//    {
		//        ViewFilterForm form = new ViewFilterForm(this.m_Model, table, field, value, "");
		//        filterClause = form.ClauseFromInitialInput();
		//    }
		//    // creates the table passing the filter
		//    AdhocView(table, filterClause);
		//}

		// behaviour when status bar panels are clicked
        private void statusBar1_PanelClick(object sender, StatusBarPanelClickEventArgs e)
        {
			// Filter panel logic
            if (e.StatusBarPanel == statusBar1.Panels[3])  // 4th panel is filter info.
            {
				// only relevant for data-views.
//                if (m_CurrentState.m_DisplayType == DisplayType.CustomView)
//                {
//                    DbConfigurableView view = (DbConfigurableView)this.m_Model.DbView;
//                    // if the filter is set then clear it otherwise show the dialog.
//                    if (view.ViewParams.FilterClause.Length == 0
//                           // .. or the filter results in no rows
//                           // decided this extra behaviour is too complicated
//                           // || theDset.Tables[0].Rows.Count == 0 
//                        )
//                    {
//                        String table = theDset.Tables[0].TableName;
////                        this.SetFilter(table, "", "");
//                    }
//                    else
//                    {
//                        view.ViewParams.FilterClause = "";
//                        try
//                        {
//                            this.do_table_search(m_NewState);
//                        }
//                        catch (DbViewApplicationException ex)
//                        {
//                            this.displayExceptionMessage(ex, "Filter clear failed");
//                        }
//                    }
//                }
            }
            // clicked on connection info.
            else if (e.StatusBarPanel == statusBar1.Panels[0])
            {
				// pop up the connections dialog.
				// nb: intention is to give access to the connection info for copying.
                this.fileManageConnections_Click(this, new EventArgs());
            }
            // copy the table name into the clipboard.
            else if (e.StatusBarPanel == statusBar1.Panels[1]) // table/view name
            {
				Clipboard.SetText(statusBar1.Panels[1].Text);
            }
        }

        // selects whether to use the new form or the original
        private bool wantAltOpenForm()
        {
            int connCount = 0;
            int tagCount = 0;
            String connName;
            foreach (connInfo ci in m_Model.ConnectionList)
            {
                ++connCount;
                connName = ci.Name.ToUpper();
                if (connName.IndexOf("DEV") != -1) ++tagCount;
                if (connName.IndexOf("QC") != -1) ++tagCount;
                if (connName.IndexOf("QA") != -1) ++tagCount;
                if (connName.IndexOf("UAT") != -1) ++tagCount;
                if (connName.IndexOf("BETA") != -1) ++tagCount;
                if (connName.IndexOf("PROD") != -1) ++tagCount;
            }
            if (connCount >= 12)    // you can handle 12 surely?
                if (tagCount >= 4)  // check there are enough special tags
                    return true; 
            return false;
        }
        /////////////////////////////////////////////////////////////////////////////        
        // menu handlers
        /////////////////////////////////////////////////////////////////////////////        
        
        /////////////////////////////////////////////////////////////////////////////        
        // file
        /////////////////////////////////////////////////////////////////////////////        
        private void fileConnect_Click(object sender, System.EventArgs e)
        {
            // experimental. Merge edit and select database connections
            if (m_Model.ConnectionList.Count == 0)
                MessageBox.Show(this,"Please enter connection information in the grid that follows",
                                     "Database connection details required",
                                     MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            fileManageConnections_Click(sender, e);    
            return;            
/*
            // bootstrap start-up
            if (m_Model.ConnectionList.Count == 0)
            {
                MessageBox.Show(this,"Please enter connection information in the grid that follows");
                fileManageConnections_Click(sender, e);    
                return;
            }
            
//            String currentConn = m_NewState.m_connection_tag;
			String currentConn = m_CurrentState.m_connection_tag;
			if (currentConn.Length == 0)
                if (mruMenu.NumEntries > 0)
                    currentConn = mruMenu.GetFileAt(0);

            // connect
            if (wantAltOpenForm())
            {
                using (OpenConnectionFormEx openDlg = new OpenConnectionFormEx(this.m_Model, currentConn))
                {
					if (openDlg.ShowDialog(this) == DialogResult.OK)
					{
						currentConn = openDlg.connectionName;
						OnChangeConnection(currentConn);
					}
				}
            }
            else
            {
                using (OpenConnectionForm openDlg = new OpenConnectionForm(this.m_Model, currentConn))
                {
					if (openDlg.ShowDialog(this) == DialogResult.OK)
					{
						currentConn = openDlg.connectionName;
						OnChangeConnection(currentConn);
					}
				}
            }
*/
        }

		//private void menuLaunchNew_Click(object sender, EventArgs e)
		//{
		//    this.LaunchNewInstance();
		//}

        private void File_Exit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void fileManageConnections_Click(object sender, System.EventArgs e)
        {
            String connection_tag = m_NewState.m_connection_tag;
            if (connection_tag.Length == 0)
                if (mruMenu.NumEntries > 0)
                    connection_tag = mruMenu.GetFileAt(0);
            using (ConnectionEditForm2 dlgEdConinfo = new ConnectionEditForm2(m_Model, connection_tag))
            {
				dlgEdConinfo.ShowDialog(this);
				if (dlgEdConinfo.ConnectionName.Length > 0)
				{
					this.OnChangeConnection(dlgEdConinfo.ConnectionName);
				}
			}
        }

        private void dataChangeView_Click(object sender, System.EventArgs e)
        {
            int iViewIndex = -1; //this.comboView.SelectedIndex;
			//if (iViewIndex == -1)
			//    return;
			//try 
			//{
			//    DbViewBase dbu = this.m_Model.DbView;
			//    ViewParams vp = dbu.ViewParams;

			//    using (ViewEditForm vef = new ViewEditForm(m_Model, vp))
			//    {
			//        if (vef.ShowDialog(this) == DialogResult.OK)
			//        {
			//            // update view name in the list in order to preserve state
			//            this.comboView.Items[this.comboView.SelectedIndex] = vp.DisplayName;
			//            // update model.
			//            on_save_new_view(dbu, vp);
			//        }                    
			//    }
			//}			    				
			//catch(System.InvalidCastException exc)
			//{
			//    MessageBox.Show(this, "Cannot configure this view: {0}", exc.Message);
			//}
        }

        private void dataAddView_Click(object sender, System.EventArgs e)
        {
            // get current row
			//int iViewIndex = this.comboView.SelectedIndex;
			//// obtain the table name for a suggestion
			//String table_name = "";
			//// todo: need to modify this test.
			//if (iViewIndex == -1)
			//{
			//    // only if on the table view 
			//    //DataGridViewCell ds = results.CurrentCell;
			//    // use the currently selected cell row to obtain the table name 
			//    //table_name = theDset.Tables[0].Rows[ds.RowIndex][0].ToString();
			//    DataRow row;
			//    this.getSelectedRow(out row);
			//    table_name = row[0].ToString();
			//    AddNewView(table_name);
			//}
        }

		///////////////////////////////////////////////////////////////////////////////        
		//// Edit
		///////////////////////////////////////////////////////////////////////////////        
		//private void editCopyGrid_Click(object sender, System.EventArgs e)
		//{
		//    int count = this.theDset.Tables[0].Rows.Count;
		//    for (int idx = 0; idx < count; ++idx)
		//        this.results.Rows[idx].Selected = true;
		//}
        
		//private void editFieldDescription_Click(object sender, System.EventArgs e)
		//{
		//    if (m_CurrentState.m_DisplayType == DisplayType.FieldMetaData)     
		//    {
		//        // need field:
		//        DataRow row;
		//        this.getSelectedRow(out row);
		//        String field_name = row[0].ToString();
		//        String field_info = row[1].ToString();
		//        // should only be here when this cast is valid.
		//        DbViewMetaData mdView = (DbViewMetaData)this.m_Model.DbView;
		//        String table_name = mdView.TableName;
		//        // code the linefeeds
		//        field_info = DbViewMetaData.decodeLineFeeds(field_info);
		//        MetaDataEditorForm editor = new MetaDataEditorForm(this.m_Model, table_name, field_name, field_info);
		//        editor.ShowDialog(this);
		//        if (editor.DialogResult == DialogResult.OK)
		//        {
		//            row[1] = DbViewMetaData.encodeLineFeeds(editor.FieldInfo);
		//        }                    
		//    }
		//}
        /////////////////////////////////////////////////////////////////////////////        
        // Show
        /////////////////////////////////////////////////////////////////////////////        
        private void schemaTables_Click(object sender, System.EventArgs e)
        {
            // tables. 
            // set flag in controller class
//            this.comboView.SelectedIndex = -1;  // no view
            m_NewState.m_DisplayType = DisplayType.Tables;           // table
			this.changeView(m_NewState);
        }

        // schema menu item handlers
//        private void schemaViews_Click(object sender, System.EventArgs e)
//        {
//            // set flag in controller class
////            this.comboView.SelectedIndex = -1;  // no view
//            // this prevents a slight oddity of behaviour in the search text
//            if (m_CurrentState.m_DisplayType == DisplayType.Views)
//                this.m_strLastSearchTextUsed = ""; 
//            m_NewState.m_DisplayType = DisplayType.Views;           // view
//            this.changeView(m_NewState);
//        }
//        private void schemaProcs_Click(object sender, System.EventArgs e)
//        {
//            // set flag in controller class
////            this.comboView.SelectedIndex = -1;  // no view
//            m_NewState.m_DisplayType = DisplayType.Procs;           // Sp
//            this.changeView(m_NewState);
//        }
		//private void schemaFuncs_Click(object sender, System.EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Functions;        // Functions
		//    this.changeView(m_NewState);
		//}
		//private void showJobs_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Jobs;
		//    this.changeView(m_NewState);
		//}
		
		//private void showJobSteps_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.JobSteps;
		//    this.changeView(m_NewState);
		//}
		
		//private void schemaTriggers_Click(object sender, System.EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Triggers;           // Sp
		//    this.changeView(m_NewState);
		//}

		//private void schemaCalculations_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Calculated;
		//    try
		//    {
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Calculations");
		//    }
		//}

		//private void schemaDependencies_Click(object sender, EventArgs e)
		//{
		//    showDependenciesFor("");
		//}

		//private void schemaProcesses_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Processes;
		//    try
		//    {
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Processes");
		//    }
		//}

		//private void showLocks_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Locks;
		//    try
		//    {
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Locks");
		//    }
		//}

		//private void showPermissions_Click(object sender, System.EventArgs e)
		//{
		//    if (!Commit_Changes_with_confirm(true)) //ok
		//        return;

		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.Permissions;
		//    this.changeView(m_NewState);
		//}
  
		//private void showServiceBroker_Click(object sender, EventArgs e)
		//{
		//    // set flag in controller class
		//    this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.ServiceBroker;
		//    try
		//    {
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Service Broker");
		//    }
		//}


		///////////////////////////////////////////////////////////////////////////////        
		//// Favourites
		///////////////////////////////////////////////////////////////////////////////        
		//private void favourite_Click(object sender, System.EventArgs e)
		//{
		//    try 
		//    {
		//        MenuItem mi = (MenuItem)sender;
		//        String name = mi.Text;
		//        Favourite f1 = new Favourite(name);
		//        // generalise
		//        // tables. 
		//        this.comboView.SelectedIndex = -1;  // no view
				
		//        // force search as if user has type it
		//        this.comboSearchPart.Text = f1.Name;
		//        this.m_strLastSearchTextUsed = "";  // or selectin the same fav in a row will be wrong
		//        // reset view type 
		//        m_NewState.m_DisplayType = (f1.Type == 1) ? DisplayType.Tables :
		//                        (f1.Type == 2) ? DisplayType.Views :
		//                        (f1.Type == 3) ? DisplayType.Procs : DisplayType.Tables;
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Favourites");
		//    }
		//}

		//private void favouritesAdd_Click(object sender, EventArgs e)
		//{
		//    // find item
		//    DataRow row;
		//    this.getSelectedRow(out row);
		//    String itemName = row[0].ToString();
		//    // map item type to favourite type
		//    int type = (m_CurrentState.m_DisplayType == DisplayType.Tables) ? 1 :
		//               (m_CurrentState.m_DisplayType == DisplayType.Views) ? 2 :
		//               (m_CurrentState.m_DisplayType == DisplayType.Procs) ? 3 : 1;
		//    // need the connection name for association to the database
		//    String connName = m_CurrentState.m_connection_tag;
		//    // create the object and add
		//    Favourite f1 = new Favourite(itemName, type);
		//    bool bAdded = this.m_Model.FavouriteManager.add(connName, f1);
		//    if (bAdded)
		//    {
		//        this.m_Model.Legacy_SaveFavouriteInfo();
		//        // add to the menu
		//        MenuItem mi = new MenuItem(f1.ToString(), favourite_Click);
		//        this.menuFavourites.MenuItems.Add(mi);
		//    }
		//}

		//private void favouritesOrganise_Click(object sender, EventArgs e)
		//{
		//    String conn = m_CurrentState.m_connection_tag;
		//    OrganiseFavouritesForm form = new OrganiseFavouritesForm(m_Model, conn);
		//    form.ShowDialog(this);
		//    updateFavourites();
		//}


        /////////////////////////////////////////////////////////////////////////////        
        // Action
        /////////////////////////////////////////////////////////////////////////////        
        private void actionSearch_Click(object sender, System.EventArgs e)
        {
            // from menu so that Ctrl+S works
            this.comboSearchPart.Focus();
        }

		//private void actionStructure_Click(object sender, System.EventArgs e)
		//{
		//    try
		//    {
		//        // set flag in controller class
		//        //this.comboView.SelectedIndex = -1;  // no view
		//        m_NewState.m_DisplayType = DisplayType.Structure;           // Sp
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Fields");
		//    }
		//}

		//private void actionData_Click(object sender, System.EventArgs e)
		//{
		//    // get current row
		//    int iViewIndex = -1;//this.comboView.SelectedIndex;
		//    // obtain the table name for a suggestion
		//    String table_name = "";
		//    // todo: need to modify this test.
		//    if (iViewIndex == -1)
		//    {
		//        // only if on the table view 
		//        // DataGridViewCell ds = results.CurrentCell;
		//        // use the currently selected cell row to obtain the table name 
		//        // table_name = theDset.Tables[0].Rows[ds.RowIndex][0].ToString();
		//        DataRow row;
		//        this.getSelectedRow(out row);
		//        table_name = row[0].ToString();
		//        // perhaps locate a temp view with the same name as the table to avoid 
		//        // duplication and preserve any tinkering.
		//        this.AdhocView(table_name, "");
		//    }
		//}

        private void actionFind_Click(object sender, System.EventArgs e)
        {
           //actionFindInSource(DisplayType.Procs);
        }

        private void actionClearSearch_Click(object sender, System.EventArgs e)
        {
            try 
            {
                m_NewState.m_search_text = "";
                this.do_table_search(m_NewState);
            }
            catch (DbViewApplicationException ex)
            {
                this.displayExceptionMessage(ex, "Clear search");
            }
        }

        private void actionClearSearchEx_Click(object sender, System.EventArgs e)
        {
            // If there is something to search then clear
            // else find previous search
            try
            {
                if (this.comboSearchPart.Text.Length == 0 &&  // search text is empty
                    this.comboSearchPart.Items.Count > 0      // and something in history
                    )
                {
                    this.comboSearchPart.Text = this.comboSearchPart.Items[0].ToString(); // reset to most recent
                }
                else // Text is not empty or there is no previous search to use
                    this.comboSearchPart.Text = ""; // reset or keep blank
				// only state to update is search text
				m_NewState.m_search_text = this.comboSearchPart.Text;
                this.do_table_search(m_NewState); // new
            }
            catch (DbViewApplicationException ex)
            {
                this.displayExceptionMessage(ex, "Clear search");
            }
        }
        
		//private void actionFilter_Click(object sender, System.EventArgs e)
		//{
		//    if (!Commit_Changes_with_confirm(false)) //ok
		//        return;

		//    int iViewIndex = -1; //this.comboView.SelectedIndex;
		//    if (iViewIndex == -1)
		//        return;
		//    try 
		//    {
		//        String table, field, value="";
		//        DataRow row;
		//        DataGridViewCell ds = results.CurrentCell;
		//        table = theDset.Tables[0].TableName;
		//        field = theDset.Tables[0].Columns[ds.ColumnIndex].Caption;
		//        if (ds.RowIndex < theDset.Tables[0].Rows.Count)
		//        {
		//            // value = theDset.Tables[0].Rows[ds.RowIndex][ds.ColumnIndex].ToString();
		//            value = theDset.Tables[0].Rows[ds.RowIndex][ds.ColumnIndex].ToString();
		//            FieldInfo fi = GetColumnInfo(theDset.Tables[0], field);
		//            if (fi.Type == "D")
		//            {
		//                // get the culture 1st.
						
		//            }
		//        }                    
		//        this.SetFilter(table, field, value);
		//    }			    				
		//    catch(System.InvalidCastException exc)
		//    {
		//        MessageBox.Show(this, "Cannot filter this view");
		//    }

        //}
        

        private void actionProfile_Click(object sender, System.EventArgs e)
        {
            if (!Commit_Changes_with_confirm(false))
                return;

            action_Profile(sender, e, false);
        }
        private void actionProfileAll_Click(object sender, System.EventArgs e)
        {
            if (!Commit_Changes_with_confirm(false))
                return;

            action_Profile(sender, e, true);
        }

		//private void actionFieldInfo_Click(object sender, EventArgs e)
		//{
		//    try
		//    {
		//        /*
		//        // hack table name into play when this is selected from custom view
		//        if (m_CurrentState.m_DisplayType == DisplayType.CustomView)
		//            this.m_SchemaTable = this.statusBar1.Panels[1].Text;
		//        */
		//        // set flag in controller class
		//        //this.comboView.SelectedIndex = -1;  // no view
		//        m_NewState.m_DisplayType = DisplayType.FieldMetaData;           // Sp
		//        this.changeView(m_NewState);
		//    }
		//    catch (DbViewApplicationException ex)
		//    {
		//        this.displayExceptionMessage(ex, "Field Info");
		//    }
		//}

		//private void actionTest_Click(object sender, System.EventArgs e)
		//{
		//    DisplayType d = DisplayType.Aggregate;
		//    String s = d.ToString();
		//    int i = 10;
		//}

        /////////////////////////////////////////////////////////////////////////////        
        // Navigate
        /////////////////////////////////////////////////////////////////////////////        
        private void actionNavigateBack_Click(object sender, System.EventArgs e)
        {
            if (!Commit_Changes_with_confirm(false)) //ok
                return;
			try 
			{
				GridState g = this.m_Navigation.back();
				ResetState(g);
			}
			catch (DbViewApplicationException ex)
			{
				this.displayExceptionMessage(ex, "Back");
			}
		}

        private void actionNavigateForwards_Click(object sender, System.EventArgs e)
        {
            if (!Commit_Changes_with_confirm(false)) //ok
                return;

            GridState g = this.m_Navigation.forward();
            ResetState(g);
        }

        private void actionGoto_Click(object sender, System.EventArgs e)
        {
            //this.action_GotoState(sender, e);
        }
        /////////////////////////////////////////////////////////////////////////////        
        // Help
        /////////////////////////////////////////////////////////////////////////////        
		//private void helpWhere_Click(object sender, System.EventArgs e)
		//{
		//    String s = this.m_Model.Legacy_ConfigFile;
		//    MessageBox.Show(this, s, "Here");
		//}

		//private void showHistory_Click(object sender, System.EventArgs e)
		//{
		//    if (!Commit_Changes_with_confirm(true)) //ok
		//        return;
		//    // set flag in controller class
		//    //this.comboView.SelectedIndex = -1;  // no view
		//    m_NewState.m_DisplayType = DisplayType.History;
		//    this.changeView(m_NewState);
                        
		//}

        private void actionSearchSource_Click(object sender, System.EventArgs e)
        {
			//if (!Commit_Changes_with_confirm(false)) // ok
			//    return;
			//try 
			//{
			//    SourceSearchForm.searchTarget tgtIn = (m_CurrentState.m_DisplayType == DisplayType.Views) ? SourceSearchForm.searchTarget.Views :
			//                                          (m_CurrentState.m_DisplayType == DisplayType.Procs) ? SourceSearchForm.searchTarget.Procs :
			//                                          (m_CurrentState.m_DisplayType == DisplayType.Functions) ? SourceSearchForm.searchTarget.Funcs :
			//                                          (m_CurrentState.m_DisplayType == DisplayType.Tables) ? SourceSearchForm.searchTarget.Tables :
			//                                          (m_CurrentState.m_DisplayType == DisplayType.Calculated) ? SourceSearchForm.searchTarget.Calcs :
			//                                          (m_CurrentState.m_DisplayType == DisplayType.ServiceBroker) ? SourceSearchForm.searchTarget.Procs :
			//                                            SourceSearchForm.searchTarget.Undetermined;

			//    SearchSource2(m_Model.SourceSearchString, tgtIn);
			//}                
			//catch (DbViewApplicationException ex)
			//{
			//    this.displayExceptionMessage(ex, "Clear search");
			//}
        }

        private void actionAggregated_Click(object sender, EventArgs e)
        {
            //actionAggregate(0);
        }


		//private void toolsFieldSelector_Click(object sender, EventArgs e)
		//{
		//    String table = GetTableName();
		//    if (table.Length > 0)
		//    {
		//    /*
		//        FieldPickerForm form = new FieldPickerForm(this.m_Model, table);
		//        // form.ShowDialog(this); //modal mode
		//        form.Show();        // tear-off mode.
		//    */
		//        // speculative
		//        this.FieldPanel.Visible = true;
		//        this.m_FieldPanelActive = true; // preserve state
		//        this.tbFieldSelecter.Pushed = this.FieldPanel.Visible;
		//        this.OnOpenFieldPicker(table);
		//    }
		//}
		//private void toolsFieldSelector_Toggle()
		//{
		//    if (this.FieldPanel.Visible == false) // on
		//        toolsFieldSelector_Click(null, null);
		//    else
		//    {
		//        this.FieldPanel.Visible = false;
		//        this.m_FieldPanelActive = false;
		//        this.tbFieldSelecter.Pushed = this.FieldPanel.Visible;
		//    }
		//}



		//private void toolsCopyTable_Click(object sender, EventArgs e)
		//{
		//    //
		//    GetTableName();
		//    CopyTableForm form = new CopyTableForm(this.m_Model);
		//    String connName = m_NewState.m_connection_tag;
		//    form.SourceDb = connName;
		//    // attempt to use the previous 
		//    form.SourceTable = GetTableName();
		//    if (lastCopyConn == connName)
		//    {
		//        // for multiple table copy operations
		//        form.TargetDb = lastCopyTgtConn;
		//        form.TargetTable = form.SourceTable;
		//    }				
		//    else
		//        form.TargetDb = connName;
		//    form.ShowDialog(this);
		//    if (form.DialogResult == DialogResult.OK)
		//    {
		//        // resolve source and target connections
		//        String connSource = m_Model.ConnectionList[form.SourceDb].connectionString;
		//        String connTarget = m_Model.ConnectionList[form.TargetDb].connectionString;
		//        // refresh the dislpay if the table copy is in the current database
		//        if (connSource == connTarget)
		//            this.do_table_search(m_NewState);
		//    }
		//    lastCopyConn = form.SourceDb;
		//    lastCopyTgtConn = form.TargetDb;

		//}

		//private void toolsSynchTables_Click(object sender, EventArgs e)
		//{
		//    // Find the two tables
		//    DataRow sr1, sr2;
		//    int selectionCount = getTwoSelectedRows(out sr1, out sr2);
		//    if (selectionCount != 2) // two not selected
		//    {
		//        MessageBox.Show("Please select two tables", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
		//        return;
		//    }
		//    // get the names
		//    String targetTable = sr1[0].ToString(); // target ABC
		//    String sourceTable = sr2[0].ToString(); // source ABC_DDDD_TTTT

		//    // confirm we are OK to go
		//    ConfirmRefreshForm cf = new ConfirmRefreshForm(targetTable, sourceTable);
		//    DialogResult res = cf.ShowDialog(this);
		//    if (res == DialogResult.OK)
		//    {
		//        // they may have been swapped in the dialog
		//        sourceTable = cf.SourceTable;
		//        targetTable = cf.TargetTable;
		//    }
		//    else
		//        return;

		//    // Check they have the correct schema.
		//    TableSchema targetSchema = new TableSchema(m_Model, targetTable);
		//    targetSchema.Populate();
		//    // but first check whether there is a pkey
		//    FieldInfo [] Pkeys = targetSchema.PKeyFields;
		//    if (Pkeys.Length == 0)
		//    {
		//        MessageBox.Show(String.Format("Table {0} requires a primary key for this to work", targetTable), "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
		//        return;
		//    }
            
		//    TableSchema sourceSchema = new TableSchema(m_Model, sourceTable);
		//    sourceSchema.Populate();
                    
		//    ScriptingHelper helper = new ScriptingHelper(sourceTable, targetTable, targetSchema);
		//    // check the tables selected match
		//    if (helper.TablesCompare(sourceSchema) == false)
		//    {
		//        MessageBox.Show("Table schemas do not match", "Problem", MessageBoxButtons.OK, MessageBoxIcon.Error);
		//        return;
		//    }

		//    String script = helper.ScriptTableRefresh();
		//    SourceForm2 f = new SourceForm2(targetTable, script, "");
		//    f.Show();
		//}
		//private void toolsAutoRefresh_Click(object sender, EventArgs e)
		//{
		//    try 
		//    {
		//        this.RowsetRefresh(true);
		//    }
		//    catch (DbViewApplicationException exc)
		//    {
		//        this.displayExceptionMessage(exc, "Auto-Rowset refresh fail");
		//    }				
		//}

//        private void toolsAdhocQueryWindow_Click(object sender, EventArgs e)
//        {
//            String s = m_NewState.m_connection_tag;
//            AdhocQueryWindow queryWindow = new AdhocQueryWindow(this.m_Model, s);
//            queryWindow.Show();
//        }

//        private void toolsSqlTemplate_Click(object sender, EventArgs e)
//        {
//            try
//            {
//                // set flag in controller class
//                this.comboView.SelectedIndex = -1;  // no view
//                m_NewState.m_DisplayType = DisplayType.SqlTemplate;
//                this.changeView(m_NewState);
//            }
//            catch (DbViewApplicationException ex)
//            {
//                this.displayExceptionMessage(ex, "SQL Template Collection");
//            }
			
//        }
		
//        private void optionsToggleFont_Click(object sender, EventArgs e)
//        {
//            // change all this.
//            String dfFontName = "Microsoft Sans Serif";
//            String altFontName = "Courier New";
//altFontName = "Arial Unicode MS";

//            if (this.results.Font.FontFamily.GetName(0).CompareTo(altFontName) == 0)
//                this.results.Font = new System.Drawing.Font(dfFontName, 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
//            else
//                // this.results.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
//    this.results.Font = new System.Drawing.Font(altFontName, 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
//        }

		//private void ChangeFont(MenuItem m)
		//{
		//    this.optionsFontDefault.Checked = false;
		//    this.optionsFontFixed.Checked = false;
		//    this.optionsFontUnicode.Checked = false;
		//    if (m == this.optionsFontDefault)
		//        this.results.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
		//    if (m == this.optionsFontFixed)
		//        this.results.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
		//    if (m == this.optionsFontUnicode)
		//        this.results.Font = new System.Drawing.Font("Arial Unicode MS", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
		//    m.Checked = true;
		//}
		//private void optionsFont_Click(object sender, EventArgs e)
		//{
		//    ChangeFont((MenuItem)sender);
		//}
		
        private void menuAggregateOps_Popup(object sender, EventArgs e)
        {

        }

        private void menuAggCount_Click(object sender, EventArgs e)
        {
//            this.actionAggregate(1);
        }

        private void menuAggRange_Click(object sender, EventArgs e)
        {
//            this.actionAggregate(2);
        }
        private void menuAggSum_Click(object sender, EventArgs e)
        {
//            this.actionAggregate(3);
        }
/*

*/



        #endregion


		//private void OnOpenFieldPicker(String table)
		//{
		//    m_Table = table;
		//    this.textTable.Text = m_Table;
		//    this.m_MatchString = "";
		//    FieldPickerPopulate();
		//}
        
		//private void GetSchemaInfo()
		//{
		//    DataSet dset;
		//    // modify yp 
		//    Helper.GetStructure(m_Model.ConnectionString, m_Table, out dset);
		//    DataTable dt = dset.Tables[0];
		//    m_TableFieldList = new ArrayList();
		//    int iLastCol = dt.Rows.Count;
		//    for (int iRowIndex = 0; iRowIndex < iLastCol; ++iRowIndex)
		//        m_TableFieldList.Add(dt.Rows[iRowIndex][0]);
		//    dt.Rows.Clear();
		//}

		//private bool Matches(String target, String pattern)
		//{
		//    if (pattern.Length == 0) // no search set
		//        return true;
		//    // simple contains
		//    if (target.ToUpper().IndexOf(pattern.ToUpper()) >= 0)
		//        return true;
		//    return false;
		//}

		//private void PopulateFields(String strMatch)
		//{
		//    listFields.Items.Clear();
		//    if (strMatch.Length > 0)
		//        listFields.ForeColor = System.Drawing.Color.Red;
		//    else
		//        listFields.ForeColor = System.Drawing.SystemColors.WindowText;
		//    foreach(String fieldName in this.m_TableFieldList)
		//    {
		//        if (Matches(fieldName, strMatch))
		//            listFields.Items.Add(fieldName);
		//    }
		//}

		//private void setMatchString(String NewMatch)
		//{
		//    if (NewMatch.CompareTo(this.m_MatchString) == 0)
		//        return; // do nothing if nothing to do.
		//    this.m_MatchString = NewMatch;
		//    PopulateFields(this.m_MatchString);
		//}

		//private String buildClipString(ArrayList selectedFields, int maxWidth, String tableAlias)
		//{
		//    int runningCount = -2; // hack as 1st +2 unnecessary
		//    String outString = "";
		//    foreach(String s1 in selectedFields)
		//    {
		//        String s = (tableAlias.Length == 0) ? s1 :
		//                                              tableAlias+"."+s1;
		//        runningCount += 2;
		//        if (outString.Length > 0)
		//            outString += ", ";

		//        if (runningCount + s.Length > maxWidth)
		//        {
		//            outString += "\n";
		//            runningCount = 0;
		//        }    
		//        outString += s;  
		//        runningCount += s.Length;                  
		//    }
		//    return outString;
		//}
		//private String getPrefix()
		//{
		//    String prefix = "";
		//    if (this.checkprefix.Checked)
		//    {
		//        prefix = (this.textPrefix.Text.Length > 0) ? this.textPrefix.Text
		//                                                   : this.textTable.Text;
		//    }
		//    return prefix;
		//}
        
		//private void copySelected()
		//{
		//    int maxWidth = 72;     // width break 
		//    ArrayList selectedFields = new ArrayList();
		//    bool something = false;
		//    foreach(int idx in listFields.SelectedIndices)
		//    {
		//        String clipField = listFields.Items[idx].ToString();
		//        selectedFields.Add(clipField);             
		//        something = true;
		//    }
		//    if (something)
		//        Clipboard.SetText(buildClipString(selectedFields, maxWidth, getPrefix()));
		//}

		//private void btnClose_Click(object sender, EventArgs e)
		//{
		//    this.FieldPanel.Visible = false;
		//    this.m_FieldPanelActive = false;
		//    this.tbFieldSelecter.Pushed = this.FieldPanel.Visible;
		//}

		//private void FieldPickerPopulate()
		//{
		//    GetSchemaInfo();
		//    PopulateFields("");
		//}

		//private void listFields_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		//{
		//    char c = e.KeyChar;
		//    if ( (c >= '0' && c <= '9') 
		//        ||(c >= 'A' && c <= 'Z') 
		//        ||(c >= 'a' && c <= 'z') )
		//    {
		//        setMatchString(this.m_MatchString + c);
		//        e.Handled = true;
		//    }
		//    else if (c == 8)
		//    {
		//        int l = this.m_MatchString.Length;
		//        if (l > 0)
		//        {
		//            setMatchString(this.m_MatchString.Substring(0, l-1));
		//            e.Handled = true;
		//        }                
		//    }
		//    else
		//    {
		//        c = c;
		//    }
		//}

		//private void btnAll_Click(object sender, EventArgs e)
		//{
		//    setMatchString("");
		//}

		//private void listFields_SelectedIndexChanged(object sender, EventArgs e)
		//{
		//    // get into clipboard
		//    copySelected();
		//}

		//private void btnCopy_Click(object sender, EventArgs e)
		//{
		//    // get into clipboard
		//    copySelected();
		//}

		//private void btnCopyAll_Click(object sender, EventArgs e)
		//{
		//    int maxWidth = 72;     // width break 
		//    ArrayList selectedFields = new ArrayList();
		//    foreach (object o in listFields.Items)
		//    {
		//        String clipField = o.ToString();
		//        selectedFields.Add(clipField);
		//    }
		//    String tablename = (this.checkprefix.Checked) ? this.textTable.Text : "";
		//    Clipboard.SetText(buildClipString(selectedFields, maxWidth, getPrefix()));
		//}

		//private void btnCopyAllList_Click(object sender, EventArgs e)
		//{
		//    int maxWidth = 0;     // width break for single field per line
		//    ArrayList selectedFields = new ArrayList();
		//    foreach (object o in listFields.Items)
		//    {
		//        String clipField = o.ToString();
		//        selectedFields.Add(clipField);
		//    }
		//    String tablename = (this.checkprefix.Checked) ? this.textTable.Text : "";
		//    Clipboard.SetText(buildClipString(selectedFields, maxWidth, getPrefix()));
			
		//}
		//private void textTable_MouseDoubleClick(object sender, MouseEventArgs e)
		//{
		//    Clipboard.SetText(this.textTable.Text);
		//}
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args) 
        {
            String arg = "";
            if (args.GetLength(0) > 0)
                arg = args[0];
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new MainForm(arg));
        }

		// handle the odd case where certain fields mess up
		private void results_DataError(object sender, DataGridViewDataErrorEventArgs e)
		{
			if (e.RowIndex == 0)
			{
				int i = 10;
			}
		}

		private void results_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
		{
			DataGridView dgv = sender as DataGridView;
			String n = dgv.SortedColumn.Name;
			String s = dgv.SortOrder.ToString();
			//MessageBox.Show(n + " " + s);
			TableView.UpdateSort(n, (dgv.SortOrder == System.Windows.Forms.SortOrder.Descending));
		}

		private void miHelpEmail_Click(object sender, EventArgs e)
		{
			// pop up dialog asking for name and http of code project
			EmailForm Dlg = new EmailForm(GetConnectionInfo());
			Dlg.ShowDialog(this);
		}

		private void miHelpAbout_Click(object sender, EventArgs e)
		{
			AboutBox aboutDlg = new AboutBox();
			aboutDlg.ShowDialog(this);
		}

		private void editCopyGrid_Click(object sender, EventArgs e)
		{
			foreach (DataGridViewRow row in this.results.Rows)
				row.Selected = true;

		}

		private void editCopy_Click(object sender, EventArgs e)
		{
			CopyCellDataToClipBoard(this.results.GetClipboardContent());
		}
	
		private bool CopyCellDataToClipBoard(DataObject dataObject)
		{
			if (dataObject == null) return false; // can't do anything more in this situation
			Clipboard.SetDataObject(dataObject);
			return true;
		}




    }
}

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DaveDbViewSharp

United Kingdom United Kingdom
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 1 Oct 2012
Article Copyright 2012 by DaveDbViewSharp
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid