Hi @Rahul Kumar , Welcome to Microsoft Q&A,
First make sure your data is entered via binding. Your needs can be accomplished through CellFormatting and CellValidating. Since the input contains letters, I assume the input is a string. You first need to separate it into the numeric part and the letter part and deal with them separately.
For cellvaliding, when the requirements are not met, Use e.Cancel = true; to cancel the customer's operation.
using System.Collections.Generic;
using System.Windows.Forms;
namespace _10_30_x
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4))
{
string originalValue = e.Value as string;
if (!string.IsNullOrEmpty(originalValue))
{
string numericPart = string.Empty;
string nonNumericPart = string.Empty;
foreach (char c in originalValue)
{
if (char.IsDigit(c) || c == '.' || c == ',')
{
numericPart += c;
}
else
{
nonNumericPart += c;
}
}
if (!string.IsNullOrEmpty(numericPart))
{
if (decimal.TryParse(numericPart, out decimal parsedValue))
{
e.Value = parsedValue.ToString("N2") + nonNumericPart;
e.FormattingApplied = true;
}
}
}
}
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 2 || e.ColumnIndex == 3 || e.ColumnIndex == 4)
{
string value = e.FormattedValue.ToString();
foreach (char c in value)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(value, "^[a-zA-Z0-9,.]*$"))
{
e.Cancel = true;
MessageBox.Show("Only numbers, letters and commas are allowed.");
break;
}
}
}
}
class goods
{
public string name { get; set; }
public string count1 { get; set; }
public string count2 { get; set; }
public string count3 { get; set; }
public string count4 { get; set; }
}
private void Form1_Load(object sender, System.EventArgs e)
{
List<goods> goods = new List<goods> { };
goods.Add(new goods() { name = "apple", count1 = "1", count2 = "26666av", count3 = "3", count4 = "4" });
goods.Add(new goods() { name = "banana", count1 = "1", count2 = "226663gg", count3 = "66663", count4 = "4" });
goods.Add(new goods() { name = "orange", count1 = "1", count2 = "24", count3 = "35", count4 = "4" });
dataGridView1.DataSource = goods;
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.