• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 439
  • Last Modified:

Unable to Format Specific Text Within a C# Application

I have attempted for several hours to get text that starts with the word "Credit Card Number: " and has an actual number to turn red, and I have only had a portion of the code that I have attached turn the text in the RichTextBox red. In addition to that, I am receiving an index error when I am attempting to search for all entries to be highlighted that a user enters in a Literal search that they are doing on data from a flat file that should highlight the term that they are searching for if the Literal Search Check Box is checked. Could someone let me know what I am doing wrong syntactically with the C# code that has been attached that is not enabling me to have all of these lines of data properly formatted either in red font color or being highlighted in yellow if the term is entered in the literal search box and the literal search box is checked.

Any help that could be provided would be greatly appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Windows;
////using System.Windows.Controls;

namespace FTransViewer
{
    public partial class FTransMain : Form
    {
        DataTable Results = new DataTable("FTRANS");
        ArrayList credit_prefixes = new ArrayList();
        CCPrefixes values = new CCPrefixes();

        ////Declare Global Variables
        //System.Collections.Generic.List<PaymentRecord> records = new System.Collections.Generic.List<PaymentRecord>();
        //System.Collections.Generic.List<PaymentRecord> results = new System.Collections.Generic.List<PaymentRecord>();
        //System.Collections.Generic.List<PaymentRecord> refine = new System.Collections.Generic.List<PaymentRecord>();


        ArrayList thirdPartyCOM = new ArrayList();

        PaymentRecord record = new PaymentRecord();
        INIFileReader file_values;// = new INIFileReader();
        int DATELENGTH = 19;
        //int COUNTER = 0;
        //int REFINE_COUNTER = 0;
        //bool compound = false;
        //bool refined = false;

        public FTransMain()
        {
            InitializeComponent();
        }//end FTransMain()

        private void FTransMain_Load(object sender, EventArgs e)
        {
            //Set the Format of the Time Date Pickers
            dateTimePicker3.Format = DateTimePickerFormat.Time;
            dateTimePicker3.ShowUpDown = true;
            dateTimePicker4.Format = DateTimePickerFormat.Time;
            dateTimePicker4.ShowUpDown = true;
            
            //Add Columns to the Data Table
            Results.Columns.Add("RecordNum", typeof(string));
            Results.Columns.Add("TransactionDateTime", typeof(DateTime));
            Results.Columns.Add("TransactionPacketType", typeof(string));
            Results.Columns.Add("CreditCardNumber", typeof(string));
            Results.Columns.Add("ThirdParty", typeof(string));
            Results.Columns.Add("RawData", typeof(string));
            Results.Columns.Add("ThirdPartyCard", typeof(string));


            //Declare Local Variables
            int counter = 0;
            List<string> filteredItems = new List<string>();
            
            //Initialize the Variables
            file_values = new INIFileReader("C:\\test\\creditprefix.ini");
            file_values.process_INIFile();
            credit_prefixes = file_values.get_creditprefixes();
            thirdPartyCOM = file_values.get_ThirdPartyCOM();

//            counter = 0;
//            while (counter < thirdPartyCOM.Count - 1)
//            {
////                comboBox1.Items.Add(((string)thirdPartyCOM[counter]));
//                counter++;
//            }//end while

            counter = 0;
            while (counter < credit_prefixes.Count - 1)
            {
                if (!filteredItems.Contains(((CCPrefixes)credit_prefixes[counter]).get_PrefixCCDescription()))
                    filteredItems.Add(((CCPrefixes)credit_prefixes[counter]).get_PrefixCCDescription());
                counter++;
            }//end while

            foreach (string description in filteredItems)
            {
                comboBox2.Items.Add(description);
            }//end foreach

            comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox2.SelectedIndex = 0;
           // comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
           // comboBox1.SelectedIndex = 0;

        }//end FTransMain_Load()

        private string find_TransactionPacket(string value)
        {
            //Determine what type of record TransType is
            string TransactionPacketType = value.Substring(21, 1);
            if (TransactionPacketType == "S")
                TransactionPacketType = "Sent";
            else if (TransactionPacketType == "R")
                TransactionPacketType = "Received";

            return TransactionPacketType;

        }//end find_TransactionPacket

        private string find_ThirdPartyCommunication(string line)
        {
            //Declare Local Variables
            string ThirdParty = "";

            //Determine the card type that is being used in the transaction
            if (line.Contains("Access"))
                ThirdParty = "Access";
            else if (line.Contains("Comdata"))
                ThirdParty = "Comdata";
            else if (line.Contains("Tchek"))
                ThirdParty = "Tchek";
            else if (line.Contains("Fleet One"))
                ThirdParty = "Fleet One";
            else if (line.Contains("EFS"))
                ThirdParty = "EFS";
            else if (line.Contains("TCH"))
                ThirdParty = "TCH";
            else if (line.Contains("FDIS"))
                ThirdParty = "FDIS";
            else if (line.Contains("MLS"))
                ThirdParty = "MLS";

            return ThirdParty;
        }//end find_ThirdPartyCommunication


        private string find_third_party(ArrayList value, string CCNumber)
        {
            //Declare Local Variables
            int counter = 0;
            bool found = false;
            string temp = "";
            //string holder = "";

            //Find the value of the credit card number
            while (counter < value.Count && !found)
            {
                if (CCNumber.Contains(((CCPrefixes)value[counter]).get_PrefixNum()))
                {
                    found = true;
                    temp = ((CCPrefixes)value[counter]).get_PrefixCCDescription();
                }//end if

                else
                {
                    counter++;
                }//end else
            }//end while
            return temp;
        }//end find_third_party



        private void openNewDATFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Declare Local Variables
            string line = "";
            DateTime output;
            bool first_run = true;
            string temp = "";
            string CommunicationType = "";
            string ThirdPartyComm = "";
            string CreditCardNum = "";
            string ThirdPartyCardType = "";
            string TransactionTime = "";
            int index = 1;

            //Allow the user to select the file to be read in
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string txtfile = openFileDialog1.FileName;
                try
                {
                    System.IO.StreamReader file = new System.IO.StreamReader(txtfile);

                    //Read through all of the lines in the text file
                    while ((line = file.ReadLine()) != null)
                    {
                        //Verify that the line is long enough to be validated by the date function
                        if (line.Length > DATELENGTH)
                        {
                            if (DateTime.TryParse(line.Substring(0, DATELENGTH), out output) && first_run)
                            {
                                first_run = false;
                            }//end if

                            else if (DateTime.TryParse(line.Substring(0, DATELENGTH), out output))
                            {
                                //Parse through the RawData in the temp variable and find the credit card number
                                temp = remove_spaces(temp); //Remove the spaces within the string
                                CommunicationType = find_TransactionPacket(line);
                                ThirdPartyComm = find_ThirdPartyCommunication(output.ToString());
                                CreditCardNum = validate_card_num(find_card_num(temp));
                                ThirdPartyCardType = find_third_party(credit_prefixes, CreditCardNum);
                                //TransactionTime = output.ToString();
                               
                                Results.Rows.Add(index.ToString(), output, CommunicationType, CreditCardNum, ThirdPartyComm, temp, ThirdPartyCardType);

                                //Reset the values
                                temp = "";
                                CommunicationType = "";
                                ThirdPartyComm = "";
                                CreditCardNum = "";
                                ThirdPartyCardType = "";
                                TransactionTime = "";
                                index++;

                            }//end else if

                            else
                            {
                                temp += line;
                            }//end else

                        }//end if

                        else
                        {
                            temp += line;
                        }// end else

                        
                    }//end while

                    file.Close();

                }// end try

                catch (IOException)
                { }// end catch

            }//end if
        }//end openNewDATFileToolStripMenuItem_Click()

        private string validate_card_num(string value)
        {
            //Declare Local Variables
            bool invalid = false;

            if (value.Length < 12 || value.Length > 20)
                invalid = true;
            //else if

            if (invalid)
                return "";
            else
                return value;

        }//end validate_card_num

        private string find_card_num(string temp)
        {
           //Declare Local Variables
            int counter = 0;
            int index = 0;
            bool found = false;
            string cardnum = "";

            while (counter < credit_prefixes.Count - 1 && !found)
            {
                if (temp.Contains(((CCPrefixes)credit_prefixes[counter]).get_PrefixNum()))
                    found = true;
                else
                    counter++;
            }

            if (found)
            {
                index = temp.IndexOf(((CCPrefixes)credit_prefixes[counter]).get_PrefixNum());
                while (index < (temp.Length - 1) && temp[index] != ',' && temp[index] != '/' && temp[index] != '=')
                {
                    cardnum += temp[index];
                    index++;
                }//end while

            }//end if

            return cardnum;
        }//end find_card_num

        private string remove_spaces(string temp)
        {
            //Declare Local Variables
            int counter = 0;
            string result = "";

            if (counter < temp.Length)
            {
                while (counter < (temp.Length - 1))
                {
                    if (temp[counter] != ' ')
                    {
                        result += temp[counter];
                        counter++;
                    }//end if

                    else
                        counter++;
                }//end while       
            }//end if

            return result;
        }//end remove_spaces()

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

        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //Declare Local Variables
            string strSelect = "";
            bool first_pass = true;
            int index = 0;
            string FromDateTime = "";
            string ToDateTime = "";
            string temp = "";
            richTextBox1.Clear();

            if (CreditCardNumCheckBox.Checked)
            {
                if (first_pass)
                {
                    strSelect = "RecordNum Like '*" + txtCardNum.Text + "*'";
                    first_pass = false;
                }//end if

            }//end if

            if (DateChkBox.Checked)
            {
                //Query Date Range Using LINQ
                FromDateTime = dateTimePicker1.Value.ToShortDateString() + " " + dateTimePicker3.Value.ToShortTimeString();
                ToDateTime = dateTimePicker2.Value.ToShortDateString() + " " + dateTimePicker4.Value.ToShortTimeString();

                if (first_pass)
                {
                    strSelect = "TransactionDateTime > #" + FromDateTime + "# AND TransactionDateTime < #" + ToDateTime + "#";
                    first_pass = false;
                }//end if

                else
                {
                    strSelect += " AND TransactionDateTime > #" + FromDateTime + "# AND TransactionDateTime < #" + ToDateTime + "#";
                }//end else
                
             }//end if


            if (CardTypeChkBox.Checked)
            {
                index = comboBox2.SelectedIndex;

                if (first_pass)
                {
                    strSelect = "ThirdPartyCard = '" + comboBox2.Items[index].ToString() + "'";
                    first_pass = false;
                }//end if

                else
                {
                    strSelect += " AND ThirdPartyCard = '" + comboBox2.Items[index].ToString() + "'";
                }//end else
            }//end if

            if (LiteralSrchBox.Checked)
            {
                if (first_pass)
                {
                    strSelect = "RawData Like '*" + txtLiteral.Text + "*'";
                    first_pass = false;
                }//end if

                else
                {
                    strSelect += " AND RawData Like '*" + txtLiteral.Text + "*'";
                }//end else
            }//end if

            if (CreditCardNumCheckBox.Checked || DateChkBox.Checked || CardTypeChkBox.Checked || LiteralSrchBox.Checked)
            {
                DataRow[] find = Results.Select(strSelect);

                if(find.Length > 100)
                {
                    index = 0;
                    while(index < 100)
                    {
                        richTextBox1.Text += "Result Number: " + index.ToString() + "\n";
                        richTextBox1.Text += "Transaction Date/Time: " + find[index]["TransactionDateTime"].ToString() + "\n";
                        richTextBox1.Text += "Data Packet Type: " + find[index]["TransactionPacketType"].ToString() + "\n";
                        richTextBox1.Text += "Third Party Contacted: " + find[index]["ThirdParty"].ToString() + "\n";
                        richTextBox1.Text += "Third Party Card Type: " + find[index]["ThirdPartyCard"].ToString() + "\n";
                        richTextBox1.Text += "Credit Card Number: ";
                        //CC_Color(find[index]["CreditCardNumber"].ToString());
                        richTextBox1.Text += find[index]["CreditCardNumber"].ToString() + "\n";
                        //CC_Color(find[index]["CreditCardNumber"].ToString());
                        //CC_Color_Reset();
                        richTextBox1.Text += "Raw Data From FTrans: " + find[index]["RawData"].ToString() + "\n";
                        richTextBox1.Text += "\n\n";
                        index++;
                    }//end while
                }//end if

                else
                {
                    index = 0;
                    while(index < find.Length -1)
                    {
                        richTextBox1.Text += "Result Number: " + index.ToString() + "\n";
                        richTextBox1.Text += "Transaction Date/Time: " + find[index]["TransactionDateTime"].ToString() + "\n";
                        richTextBox1.Text += "Data Packet Type: " + find[index]["TransactionPacketType"].ToString() + "\n";
                        richTextBox1.Text += "Third Party Contacted: " + find[index]["ThirdParty"].ToString() + "\n";
                        richTextBox1.Text += "Third Party Card Type: " + find[index]["ThirdPartyCard"].ToString() + "\n";
                        richTextBox1.Text += "Credit Card Number: ";
                        //CC_Color(find[index]["CreditCardNumber"].ToString());
                        richTextBox1.Text += find[index]["CreditCardNumber"].ToString() + "\n";
                        //CC_Color_Reset();
                        //CC_Color(find[index]["CreditCardNumber"].ToString());
                        richTextBox1.Text += "Raw Data From FTrans: " + find[index]["RawData"].ToString() + "\n";
                        richTextBox1.Text += "\n\n";
                        index++;
                    }//end while
                }//end else

                if (find.Length > 100)
                {
                    index = 0;
                    int i = 0;
                    while (index < 100)
                    {
                        temp = "Credit Card Number: " + find[index]["CreditCardNumber"].ToString();
                        i = richTextBox1.Text.IndexOf(temp);
                        richTextBox1.SelectionStart = i;
                        richTextBox1.SelectionLength = temp.Length;
                        richTextBox1.SelectionColor = Color.Red;

                        index++;
                        i = 0;
                    }//end while
                }//end if

                else
                {
                    index = 0;
                    int i = 0;
                    while (index < find.Length - 1)
                    {
                        temp = "Credit Card Number: " + find[index]["CreditCardNumber"].ToString();
                        i = richTextBox1.Text.IndexOf(temp);
                        richTextBox1.SelectionStart = i;
                        richTextBox1.SelectionLength = temp.Length;
                        richTextBox1.SelectionColor = Color.Red;

                        index++;
                        i = 0;
                    }//end while
                }//end else

                if (LiteralSrchBox.Checked)
                {
                    index = 0;
                    while (index < richTextBox1.TextLength - 1)
                    {
                        index = richTextBox1.Text.IndexOf(txtLiteral.Text);
                        richTextBox1.SelectionStart = index;
                        richTextBox1.SelectionLength = txtLiteral.Text.Length;
                        richTextBox1.SelectionBackColor = Color.Yellow;
                        index++;
                    }//end while
                }//end if

                strSelect = "";
            }//end if

        }//end btnSearch_Click()

        private void CC_Color(string value)
        {
            
            
            //if (value != "")
            //{
            //    int start = richTextBox1.Text.IndexOf(value);

            //    richTextBox1.SelectionStart = start;
            //    richTextBox1.SelectionLength = value.Length;
            //    richTextBox1.SelectionColor = Color.Red; 
            //}//end if
        }//end CC_Color

        private void CC_Color_Reset()
        {
            //richTextBox1.ForeColor = Color.Black;
        }


        private void btnClear_Click(object sender, EventArgs e)
        {
            txtCardNum.Text = "";
            txtLiteral.Text = "";
            CreditCardNumCheckBox.Checked = false;
            DateChkBox.Checked = false;
            CardTypeChkBox.Checked = false;
            LiteralSrchBox.Checked = false;
            richTextBox1.Clear();
        }//end btnClear_Click


        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            //Does Nothing
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Reset the search Criteria and Results
            //results.Clear();
            //refine.Clear();
            CreditCardNumCheckBox.Checked = false;
            //CreditCardLast4.Checked = false;
            DateChkBox.Checked = false;
            //TransTypeTxtBox.Checked = false;
            LiteralSrchBox.Checked = false;
            //textBox1.Text = "";
            //COUNTER = 0;
            //REFINE_COUNTER = 0;
            //compound = false;
            //refined = false;
           // clear_results();
            richTextBox1.Clear();
        }//end button1_Click

        private void contextMenuStrip2_Opening_1(object sender, CancelEventArgs e)
        {
            //Do Nothing
        }//end contextMenuStrip2_Opening_1

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }//end copyToolStripMenuItem_Click

    }//end FTransMain
}//end FTransViewer namespace

Open in new window

0
thenthorn1010
Asked:
thenthorn1010
  • 2
1 Solution
 
mcs0506Commented:
Hi,
I have analyzed your code, you used while loop against index counter, try to use foreach loop instead of while loop. foreach will remove an index error. And for text red color i am unable to understand as per my suggestion you can write "Credit Card Number: " in lable and the actual credit card number in textbox to set its back color or fore color property to red. If not solved your problem then please send all form related files or sample project containing this form.

regards

Dani
0
 
thenthorn1010Author Commented:
mcs0506,

THank you for your quick response. I do not think that I will be able to use a foreach loop because I am only displaying the first 100 records out of the results of a datasearch completed by a user. As a result, I need to be able to go back into the richTextbox1 control and be able to highlight all of the information entered in the Literal Search Box as well as be able to change the font color when the user is viewing all lines that have the word "Credit Card Number:" and the corresponding data that follows the "Credit Card Number" within the richTextbox1 control.

I have attached the complete project to this posting for you to review. Any help that you could provide would be greatly appreciated. I have attached a  (I have spent close to 6 hours just trying to change colors and highlight the text without changing the background color and the font color for the entire richTextbox1 control itself. )
FTransViewer.sln
FTransMain.Designer.cs
FTransMain.cs
CCPrefixes.cs
INIFileReader.cs
0
 
mcs0506Commented:
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now