Strange code, how make it better?
Hi!
I stumbled upon this code in a project
Code:
private void TextBox_KeyDown(object sender, KeyEventArgs e) {
var t = (TextBox)sender;
if (t.IsReadOnly == true && e.Key != Key.F2) {
t.Text = "";
t.IsReadOnly = false;
}
if (e.Key == Key.F2) {
t.IsReadOnly = false;
t.CaretIndex = t.Text.Length;
t.Cursor = Cursors.IBeam;
e.Handled = true;
}
}
I asked around and it seems like there is a requirement that a cell in a datagrid shoould get some "excel-like" behaviour. For example, when you select a cell and start type, the existing text disappear, and when you press f2 or double click, the cursor should be positioned at the end of the text.
Im a web guy myself and want to ask the experts here ifall this code is really needed, and if something can be done to make it look more "pretty", for example, is e.handle really needed and what about the if- statements?
kind regards
Henrik
Re: Strange code, how make it better?
The code that you have is C#. This is how it'd look in vb.net:
Code:
Private Sub TextBox_KeyDown(sender As Object, e As KeyEventArgs)
Dim t As TextBox = DirectCast(sender, TextBox)
If t.IsReadOnly = True AndAlso e.Key <> Key.F2 Then
t.Text = ""
t.IsReadOnly = False
End If
If e.Key = Key.F2 Then
t.IsReadOnly = False
t.CaretIndex = t.Text.Length - 1
t.Cursor = Cursors.IBeam
e.Handled = True
End If
End Sub
That says that if the textbox is readonly and the key that was pressed wasn't F2 then set the text to String.Empty and set the textbox's readonly to false. If that first condition fails and the key is F2, then the textbox's readonly is set to false the Caret is set to the end of the text, the Cursor is the I beam, like a regular textbox, and a true value for Handled prevents most handlers along the event route from handling the same event again.
Edit - The only thing different I'd do is: instead of having 2 if/then statements, I'd have an If/Then...ElseIf/Then...End If format:
Code:
If (condition1) Then
'Matches condition1
ElseIf (condition2) Then
'Doesn't match condition1, but matches condition2
Else
'Doesn't match condition1 or condition2
End If
Re: Strange code, how make it better?
@Henrik: Are you looking for a C# Solution or a VB.net Solution?
Re: Strange code, how make it better?
Quote:
Originally Posted by
koolsid
@Henrik: Are you looking for a C# Solution or a VB.net Solution?
Hi!
Either would be fine, but I guess we can call the issue solved, thanks!