Wednesday, August 11, 2010

In VB.net, how can I check to see if the changes made to a datagrid cell are valid before committing the edit?

One of the cells of the datagrid is numeric data only. If the user enters any other character, an error occurs but I have no place to catch the exception. I know there must be a way to do it within the mydatagrid_cellendedit but I can't seem to figure it out. Any help would be greatly appreciated.In VB.net, how can I check to see if the changes made to a datagrid cell are valid before committing the edit?
Hello. Like the gentleman above I have not used datagrids to update data in a while. I beg your pardon if my syntax is incorrect, but I imagine if you play around for a while you can get it. I also am assuming you're creating a windows application. Can you please specify what you are using to develop? Visual Studio 2003/2005, web matrix?





I imagine if there is some server side event being called when you leave the cell, could be something like myDataGrid_ItemUpdated something like that. On that event you could check the value of the cell to see if it's numeric and then if it's not just set a label saying only numeric values allowed.





*Update: Just spent a little bit of time looking at this. Hope this helps. It's done using VS 2005. By the way I was forced to put spaces at the end of lines so it would show up in the forum. Let me know if you have any other questions.





Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEve鈥?Handles DataGridView1.CellValueChanged





If e.RowIndex %26gt;= 0 Then


Try


'if you can convert the cell to a number then it is a number


'0 is the cell that you would want to be checking for a number


Dim intPlaceHolder As Integer = CType(DataGridView1.Rows(e.Row


Index).Cells(0).Value.ToString (), Integer)


lblError.Text = ';fine';


Catch ex As Exception


lblError.Text = ';Not Fine';


Exit Sub


End Try


End If


End SubIn VB.net, how can I check to see if the changes made to a datagrid cell are valid before committing the edit?
Hmmm.... I don't have access to .Net right now, and it's been a while since I worked with datagrids in it. Is the error presenting as soon as you enter the data, or after you take some kind of action? If an error is being generated when you take an action, like clicking a button, you may be able to find out the exact error number (can't remember how to do it offhand in VB..something like 'Err.Message') and put a catch in for that specific error, prompting the user to enter a numerical value. If it is happening when entering into the datagrid, then you may want to prevent anyone from entering values directly into the grid, and instead have them enter them in a form, where you can validate them, then pass the values along to the datagrid. Hope this helps - good luck.

No comments:

Post a Comment