Hi
I have a question regarding the datagridview cellFormatting event in C#,

if (e.ColumnIndex >= 0)
            {
                if (this.dgvSubContractor.Columns[e.ColumnIndex].Name == "TelNo")
                {
                    if (e.Value != null)
                    {
                        this.dgvSubContractor[3, row].Value = c.CheckingValue(e.Value.ToString()).ToString();
                    }

                }
                return;
            }

I wrote the below code to format a 10 digit number to (456) 123-7890
But when I add a new row the previous value of the tel no will display in the newly added row,
How can I avoid this.

Whats this method: c.CheckingValue() ?

hey that is for formatting the tel no

public string CheckingValue(string Value)
        {

            long value = 0;

            string str = Value;
            bool bChecking = long.TryParse(str, out value);
            if (bChecking)
            {
                str = String.Format("{0:(###) ###-####}", value);                
            }
            
            return str;
        }

Change this row to:

this.dgvSubContractor[3, row].Value.ToString() = c.CheckingValue(e.Value.ToString()).ToString();

and btw, this is not a good way to check for the number. What happenes in case if the string you check in the "CheckingValue" method is not a number? In your case nothing, only the form of tel. number will not the ok (maybe tel. number will include letters).
And your checking method here is completely wortheless - why? Because in any case you return string. Even ifs its not a number.
You have to set the method to bool modifier and return true or false. If true, set the string to a tel. number format, if not, warn the user he entered wrong string.

Something like:

private void PopulatingDGV()
        {
            //... code

            if (e.ColumnIndex >= 0)
            {
                if (this.dgvSubContractor.Columns[e.ColumnIndex].Name == "TelNo")
                {
                    if (e.Value != null)
                    {
                        string value = e.Value.ToString();
                        bool bChecking = c.CheckingValue(value);
                        if (bChecking)
                            this.dgvSubContractor[3, row].Value.ToString() = String.Format("{0:(###) ###-####}", value);
                        else
                            MessageBox.Show("Wrong tel. number format. Please repair it...");
                    }
                }
                return;
            }
        }

        public static bool CheckingValue(string item)
        {
            long value = 0;
            bool bChecking = long.TryParse(item, out value);
            if (bChecking)
                return true;
            else
                return false;
        }

Hope this helps,
Mitja

Comments
Nice!
This article has been dead for over six months. Start a new discussion instead.