locked
Datagridview CellEndEdit event throwing input string not in correct format RRS feed

  • Question

  • see the code

            private void dgList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
            {
                if (e.RowIndex >= 0)
                {
                    if (dgList.CurrentCell.ColumnIndex == 4)
                    {
                        if (dgList.CurrentRow.Cells[4].Value != DBNull.Value)
                        {
                            //string indentValue = dgList.CurrentRow.Cells[4].Value.ToString();
                            string indentValue = dgList.Rows[e.RowIndex].Cells[4].Value.ToString();
                            if (indentValue != "")
                            {
                                if (IsNumeric(indentValue))
                                {
                                    //if (Convert.ToInt32(indentValue) < 2)
                                    //{
                                    //    MessageBox.Show("Minimum Indent Value must be 2");
                                    //    dgList.CurrentRow.Cells[4].Value = "2";
                                    //}
                                    if (Convert.ToInt32(indentValue) > 10)
                                    {
                                        MessageBox.Show("Maximum Indent Value must be 10");
                                        dgList.CurrentRow.Cells[4].Value = "0";
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Indent Value must be numeric");
                                    dgList.CurrentRow.Cells[4].Value = "0";
                                }
                            }
                            else
                            {
                                MessageBox.Show("Indent Value can not be empty");
                                dgList.CurrentRow.Cells[4].Value = "0";
                            }
                        }
                    }
                }
            }
    public bool IsNumeric(string value)
            {
                return value.All(char.IsNumber);
            }


    I search google lot but no way i could not suppress the error. Cell 4 is textbox type column. when cell 4 has numeric value then no issue then moment i change any numeric value to alphabet then a error message comes like input string not in correct format

    no way i can not handle this situation. i set the break point in the begining of the event but controls not going to stuck there.

    how to resolve this issue. i even comment all the lines inside of the above event but still getting this error when insert alphabet in cell 4. this behavior not clear. why it is happening. please help.



    • Edited by Sudip_inn Wednesday, October 28, 2020 12:21 PM
    Wednesday, October 28, 2020 12:18 PM

Answers

  • This forum is for C#-specific questions only. Questions related to Windows Forms including DataGridView should be posted in the new Microsoft Q&A forums.

    Also that is not a good way to check for ints. If you need to determine if a string is an int then simply use Int32.TryParse. You should really never use Convert.To unless you have an object that isn't a string. In all other cases use the faster/safer TryParse methods that all the primitives have. With it you can easily rewrite that entire method into a couple lines of code.

    private void dgList_CellEndEdit ( object sender, DataGridViewCellEventArgs e )
    {
       if (e.RowIndex < 0 || dgList.CurrentCell.ColumnIndex != 4)
          return;
    
       var cell = dgList.CurrentRow.Cells[dgList.CurrentCell.ColumnIndex];
       var indentValue = (cell.Value != DBNull.Value) ? cell.Value?.ToString();
    
       if (Int32.TryParse(indentValue, out var indent))   
          if (index <= 10)
             cell.Value = indent;
          else
             MessageBox.Show(...);
       else
          MessageBox.Show(...);
    }
    The folks over on Q&A can probably help you better but my guess is that you are using a FormatString on the cell and you expect the underlying value to be an int. However in the code it is getting set to a string and thus the format specifier is invalid. You can google for this problem as it happens a lot. Otherwise please post over in the correct forum for more help.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Sudip_inn Thursday, October 29, 2020 7:54 AM
    Wednesday, October 28, 2020 1:53 PM
  • Finding anything on the new Q&A forums is a bit of a pain, I think. Here's a link that will take you directly to the WindowsForms forum, which might be a good place to look around:

    https://docs.microsoft.com/en-us/answers/topics/windows-forms.html


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by Sudip_inn Thursday, October 29, 2020 7:54 AM
    Wednesday, October 28, 2020 2:57 PM
  • Hi Sudip_inn,

    I simply tested it and found the problem.

    If you use breakpoints to debug, you will find that this error occurs before the code enters the dgList_CellEndEdit event.

    The fifth column in your data source determines the data format of this column in the datagridview, if the format of your newly input data is wrong, then the datagridview will report an error directly, you don't need to judge by yourself in the code as you do now.

    The solution is simple, use DataGridView.DataError Event.

    A code example is provided in the documentation.

            private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
            {
                MessageBox.Show("Error happened " + anError.Context.ToString());
    
                if (anError.Context == DataGridViewDataErrorContexts.Commit)
                {
                    MessageBox.Show("Commit error");
                }
                if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
                {
                    MessageBox.Show("Cell change");
                }
                if (anError.Context == DataGridViewDataErrorContexts.Parsing)
                {
                    MessageBox.Show("parsing error");
                }
                if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
                {
                    MessageBox.Show("leave control error");
                }
    
                if ((anError.Exception) is ConstraintException)
                {
                    DataGridView view = (DataGridView)sender;
                    view.Rows[anError.RowIndex].ErrorText = "an error";
                    view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
    
                    anError.ThrowException = false;
                }
            }

    In addition, please follow the suggestions of Michael and Bonnie and post Windows Forms questions on Microsoft Q&A.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 29, 2020 2:26 AM

All replies

  • This forum is for C#-specific questions only. Questions related to Windows Forms including DataGridView should be posted in the new Microsoft Q&A forums.

    Also that is not a good way to check for ints. If you need to determine if a string is an int then simply use Int32.TryParse. You should really never use Convert.To unless you have an object that isn't a string. In all other cases use the faster/safer TryParse methods that all the primitives have. With it you can easily rewrite that entire method into a couple lines of code.

    private void dgList_CellEndEdit ( object sender, DataGridViewCellEventArgs e )
    {
       if (e.RowIndex < 0 || dgList.CurrentCell.ColumnIndex != 4)
          return;
    
       var cell = dgList.CurrentRow.Cells[dgList.CurrentCell.ColumnIndex];
       var indentValue = (cell.Value != DBNull.Value) ? cell.Value?.ToString();
    
       if (Int32.TryParse(indentValue, out var indent))   
          if (index <= 10)
             cell.Value = indent;
          else
             MessageBox.Show(...);
       else
          MessageBox.Show(...);
    }
    The folks over on Q&A can probably help you better but my guess is that you are using a FormatString on the cell and you expect the underlying value to be an int. However in the code it is getting set to a string and thus the format specifier is invalid. You can google for this problem as it happens a lot. Otherwise please post over in the correct forum for more help.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Sudip_inn Thursday, October 29, 2020 7:54 AM
    Wednesday, October 28, 2020 1:53 PM
  • Sorry i have used your code but still same problem persist.
    Wednesday, October 28, 2020 2:15 PM
  • I didn't say my code would fix your problem. I merely cleaned up your code because it used Convert.To.

    As I mentioned the problem is you are using a format string in the cell and the value isn't valid. Hence it crashes. If you look at the callstack it is crashing when it is trying to take the value the cell has and run it through the formatter. I'm not convinced that is happening because of the code you posted but I cannot confirm that.

    The only way to fix this is to use the correct value. But that isn't a C#-language question. Please post your question in the Q&A forums where they support the DataGridView questions.


    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, October 28, 2020 2:46 PM
  • Finding anything on the new Q&A forums is a bit of a pain, I think. Here's a link that will take you directly to the WindowsForms forum, which might be a good place to look around:

    https://docs.microsoft.com/en-us/answers/topics/windows-forms.html


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    • Marked as answer by Sudip_inn Thursday, October 29, 2020 7:54 AM
    Wednesday, October 28, 2020 2:57 PM
  • Thank you madam.
    Wednesday, October 28, 2020 3:38 PM
  • Hi Sudip_inn,

    I simply tested it and found the problem.

    If you use breakpoints to debug, you will find that this error occurs before the code enters the dgList_CellEndEdit event.

    The fifth column in your data source determines the data format of this column in the datagridview, if the format of your newly input data is wrong, then the datagridview will report an error directly, you don't need to judge by yourself in the code as you do now.

    The solution is simple, use DataGridView.DataError Event.

    A code example is provided in the documentation.

            private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
            {
                MessageBox.Show("Error happened " + anError.Context.ToString());
    
                if (anError.Context == DataGridViewDataErrorContexts.Commit)
                {
                    MessageBox.Show("Commit error");
                }
                if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
                {
                    MessageBox.Show("Cell change");
                }
                if (anError.Context == DataGridViewDataErrorContexts.Parsing)
                {
                    MessageBox.Show("parsing error");
                }
                if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
                {
                    MessageBox.Show("leave control error");
                }
    
                if ((anError.Exception) is ConstraintException)
                {
                    DataGridView view = (DataGridView)sender;
                    view.Rows[anError.RowIndex].ErrorText = "an error";
                    view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
    
                    anError.ThrowException = false;
                }
            }

    In addition, please follow the suggestions of Michael and Bonnie and post Windows Forms questions on Microsoft Q&A.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 29, 2020 2:26 AM
  • i just convert the data type from int to string and now problem solved.
    Thursday, October 29, 2020 7:53 AM
  • Morning Madam,

    How do i know for what are the topic there is a category created in MS QA forum?

    category like c#, SQL Server, TFS, Winform etc.

    is there any url from where i can see list of forum category in MS QA?

    please give your suggestion. thanks

    Thursday, October 29, 2020 7:56 AM
  • Hi Sudip_inn,

    When you try to ask a question in Microsoft Q&A, there is an option "Tags", select the relevant tag to make it appear in the right place. If you have experience using stackoverflow, you should be familiar with it.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, October 29, 2020 8:01 AM
  • i guess still now not all relevant tags has been added there. thanks
    Thursday, October 29, 2020 4:58 PM
  • Hi Sudip,

    What tag did you want to use? Unfortunately, we can't just make up a tag (and I have no idea how to request that a tag be added).

    I didn't see that you asked any questions with the windows-form tag ... didn't you want to ask a question about Windows Forms?


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Friday, October 30, 2020 4:55 AM
  • Madam there is no tag for c#. if possible please add this tag.

    i saw when we post question in microsoft QA then same question is repeating multiple times when another person is giving answer for any question. every forum show a question or post only once in main page and when user click on posted question then a page appear which show all the answer and comments there.

    i have no access to those people who develop QA web site. so please request those people to restructure MS QA like other popular forum.

    Thanks

    Thursday, November 5, 2020 11:46 AM
  • We have no control over this and they won't see your feedback here. In the top right corner of the Q&A site is a big button that says Site Feedback. Click that to send feedback about the Q&A site. Posting here won't help as we don't have any more access than you do.

    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, November 5, 2020 1:55 PM
  • Sudip, as Michael said, we don't have any access to Q&A either. I'm not crazy about the structure of the Q&A forum, but all anyone can do is give them Feedback and hopefully someone will listen.

    I also wanted to address your other item, which is a tag for C#. There is no reason to have a C# tag on the Q&A forums, because MS has not migrated this MSDN C# forum over to Q&A. So, you'll still ask C#-related questions here.


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Thursday, November 5, 2020 4:07 PM