Click here to Skip to main content
15,896,726 members
Articles / Programming Languages / C#

The Grid Processor: Word Processing Abilities for the .NET DataGridView Component

Rate me:
Please Sign up or sign in to vote.
4.87/5 (15 votes)
7 May 200711 min read 65.7K   1.6K   51  
A plugin which offers search and replace, casing and other capabilities for the Microsoft .NET DataGridView component
#region GNU notice
// GridProcessor - Search and replace abilities for the .NET DataGridView
// Copyright (C) 2007, by Evan Stein
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
#endregion GNU notice
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace GridProcessor
{
    public partial class FormSaveSplitExpression : Form
    {
        Split mSplit;
        private Settings mSettings;

        /// <summary>
        /// A form for saving a split object to the database
        /// </summary>
        /// <param name="split">The split to save</param>
        /// <param name="settings">Database connection information</param>
        public FormSaveSplitExpression(Split split, Settings settings)
        {
            InitializeComponent();
            mSettings = settings;
            mSplit = split.Clone();
        }

        private void FormSaveSplitExpression_Load(object sender, EventArgs e)
        {
            this.oleDbConnection1.ConnectionString =
                mSettings.ConnectionString;
            try
            {
                oleDbDataAdapter1.Fill(dataSetGridProcess1, "GridProcess");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Load error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
                this.Hide();
            }
            this.comboBox_names.Text = mSplit.Name;
            textBox_description.Text = mSplit.Description;
            textBox_splitExpr.Text = mSplit.SearchExpression;
            textBox_sourceColumn.Text = mSplit.SourceColumnName;
            checkBox_regex.Checked = mSplit.UseRegex;


        }

        private void button_save_Click(object sender, EventArgs e)
        {
            if (SaveSplit())
            {
                this.DialogResult = DialogResult.OK;
                this.Hide();
            }
        }

        private void button_cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Hide();
        }

        private bool SaveSplit()
        {
            DataTable dt;
            string name = string.Empty, searchName;
            int rowIndex;
            DialogResult result;
            DataRow dr;
            int splitTypeID;

            if (!CheckForSave())
                return false;

            mSplit.Name = comboBox_names.Text;
            mSplit.Description = textBox_description.Text;
            mSplit.SearchExpression = textBox_splitExpr.Text;
            mSplit.SourceColumnName = textBox_sourceColumn.Text;
            mSplit.UseRegex = checkBox_regex.Checked;
            splitTypeID = Util.GetGridProcessTypeID("Split", mSettings);

            dt = dataSetGridProcess1.Tables["GridProcess"];
            searchName = mSplit.Name.ToUpper().Trim();
            rowIndex = -1;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                name = dt.Rows[i]["Name"].ToString().ToUpper().Trim();
                if (name == searchName)
                {
                    rowIndex = i;
                    name = dt.Rows[i]["Name"].ToString();
                    break;
                }
            }
            if (rowIndex >= 0)
            {
                result = MessageBox.Show("Replace existing item [" + name + "] ?", "Replace",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (result != DialogResult.Yes)
                    return false;
                else
                    dr = dt.Rows[rowIndex];
            }
            else
            {
                dr = dt.NewRow();
                dt.Rows.Add(dr);
                mSplit.ID = -1;
            }

            dr["GridProcessID"] = mSplit.ID;
            dr["GridProcessTypeID"] = splitTypeID;
            dr["Name"] = mSplit.Name;
            dr["Description"] = mSplit.Description;
            dr["SearchExpression"] = mSplit.SearchExpression;
            dr["SourceColumnName"] = mSplit.SourceColumnName;
            dr["UseRegex"] = mSplit.UseRegex;

            try
            {
                oleDbDataAdapter1.Update(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during save: " + ex.Message, "Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if( !AddColumns() )
                return false;

            return true;
        }

        private bool AddColumns()
        {
            int splitTypeID, rowsAffected, splitID;
            OleDbCommand command;
            string commandText;
            OleDbParameter nameParam, numParam;
            object resultObj;

            splitTypeID = Util.GetGridProcessTypeID("Split", mSettings);
            // Now get the ID and save the columns
            commandText =
                "select GridProcessID from GridProcess "
                + "where GridProcessTypeID = " + splitTypeID.ToString()
                + " and Name = ?";
            // Take no chances with strings! Apostrophes and
            // silly things can throw you off. Let the
            // driver-makers worry about it, and use parameter
            nameParam = new OleDbParameter("Name", mSplit.Name);
            nameParam.OleDbType = OleDbType.VarChar;
            nameParam.DbType = DbType.String;
            command = new OleDbCommand(commandText, oleDbConnection1);
            command.Parameters.Add(nameParam);
            command.CommandText = commandText;
            oleDbConnection1.Open();
            try
            {
                resultObj = command.ExecuteScalar();
                splitID = Convert.ToInt32(resultObj);
            }
            catch( Exception ex )
            {
                MessageBox.Show(this, "Error saving columns for split [" + mSplit.Name + "]: " + ex.Message, "Save Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            // Now, delete prior columns
            commandText =
                "delete from ColumnList where GridProcessID="
                    + splitID.ToString();
            command.Parameters.Clear();
            command.CommandText = commandText;
            try
            {
                rowsAffected = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error deleting prior split columns [" + mSplit.Name + "]: " + ex.Message, "Save Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            command.Parameters.Add(nameParam);
            numParam = new OleDbParameter("SplitNum", 0);
            numParam.OleDbType = OleDbType.Integer;
            numParam.DbType = DbType.Int32;
            command.Parameters.Add(numParam);
            commandText = 
                "insert into ColumnList "
                +"(GridProcessID, ColumnName, SplitNum) "
                +"values ( " + splitID.ToString() + ", ?, ? )";
            command.CommandText = commandText;
            for (int i = 0; i < mSplit.Columns.Count; i++)
            {
                if( mSplit.Columns[i].SplitNum < 1 )
                    continue;
                command.Parameters[0].Value = mSplit.Columns[i].ColumnName;
                command.Parameters[1].Value = mSplit.Columns[i].SplitNum;
                try
                {
                    rowsAffected = command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Error inserting columns for split [" + mSplit.Name + "]: " + ex.Message, "Save Split", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            oleDbConnection1.Close();
            return true;
        }

        /// <summary>
        /// Pedantic functions removed to make the long
        /// Save function a hair shorter
        /// </summary>
        /// <returns></returns>
        private bool CheckForSave()
        {
            if (comboBox_names.Text == string.Empty)
            {
                MessageBox.Show("Split must have a name", "Save",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            if (textBox_description.Text == string.Empty)
            {
                MessageBox.Show("Split must have some sort of description", "Save",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            if (textBox_splitExpr.Text == string.Empty)
            {
                MessageBox.Show("You must supply a split expression", "Save",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
            return true;
        }

        /// <summary>
        /// The Split object being saved
        /// </summary>
        public Split Split
        {
            get { return mSplit; }
        }

    }
}

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

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

License

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

A list of licenses authors might use can be found here


Written By
United Kingdom United Kingdom
I'm a London-based software developer. Originally from New York, I came here in 1997 to run European application development for Standard & Poors. I now work independently ... and I'm still here!

Having seen how US software behaves outside the US, I'm keenly interested in problems of global and multilingual software design. I also used to write intelligence-gathering software, and still can't resist a well-turned algorithm! Before my IT career I was in music, and I'm now combining both interests in a highly-exciting 'Project-X'. I could tell you what it is, but ....

When not thinking about all of the above, I'm fascinated by all aspects of different cultures. (You can't take New York out of the New Yorker.) Interests include jazz, classical and world music, languages, history and ethnic food. I'm also an amateur travel writer and photographer, and run a site at www.travelogues.net, which you're welcome to stop by and visit!

Comments and Discussions