Click here to Skip to main content
15,912,756 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Can any1 tell me how to validate the textbox column for only month and year in datagridview (windows application).

Thanks in advance.

Regards,
Shridevi
Posted

As seen from the question it seems that the requirement is to validate the entry in the TextBoxColumn of DataGridView such that only month and year is entered. For this purpose I think the the CellValidating event of DataGridView can be used as follows:
C#
dataGridView1.CellValidating += (s, args) => {
    //If the column index is not the index of the desired column then return
    if (args.ColumnIndex != 2)
        return;
    if (!Regex.IsMatch((string)args.FormattedValue,@"\d{2}/\d{4}", RegexOptions.CultureInvariant)){
        MessageBox.Show("Please enter month and year as 05/2012");
        args.Cancel=true;
    }

};

In the above example the MM/yyyy format is used. You can check any other format including the valid ranges with appropriate regular expression pattern.
 
Share this answer
 
Comments
Maciej Los 17-May-12 9:30am    
Great! +5
VJ Reddy 17-May-12 9:52am    
Thank you, losmac :)
Sergey Alexandrovich Kryukov 18-May-12 14:08pm    
Right, a 5.
--SA
VJ Reddy 18-May-12 20:25pm    
Thank you, SA :)
shripk88 5-Jun-12 5:27am    
thanx so much.. it worked..
Simple trick: replace day for each date with 1 and now you can validate
In a DataGridView DataBindingComplete[^] event:
C#
foreach (DataGridViewRow i in dataGridView1.Rows)
{
    String s = i.Cells[Index].ToString;
    DateTime d = DateTime.Parse(s);
    d.Day = 1
    i.Cells[Index].Value = d.ToString();
}


I don't have C# compilator, so excuse me if i made an error in above code.
 
Share this answer
 
v2
Comments
shripk88 5-Jun-12 5:27am    
thanx..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900