The question is quite unclear. I have no idea where the DataGridView comes into play here, since the code is all about a textbox.
But either way, this code is not a good solution to the problem. You will continually interfere with the user's ability to change the textbox's contents, resulting in an extremely frustrating experience.
If you have to do this, make sure that you only do this when the textbox loses focus, not each time the text changes. That is, handle the LostFocus
event, rather than the TextChanged
event. You can do the same conditional test, but make sure you get the operators correct! (==
for equality testing; =
for assignment).
private void textBox3_LostFocus(object sender, EventArgs e)
{
if (textBox3.Text == "")
{
textBox3.Text = "---";
}
}
An even better solution would be to use a textbox with a cue banner. Set the cue banner to the "---" string, and it will be displayed whenever the textbox is otherwise empty (contains no text). This is all done automatically by the operating system, and handled as part of the textbox's painting logic, so it never interferes with the user's ability to interact with the control. It is also predictable and consistent with standard Windows UI behavior.
If you were actually trying to check whether a textbox is empty, and if so, add "---" to a DataGridView, then the TextChanged
event will probably work, but Validating
is an even better choice. Inside of the if
statement, assign the text to the appropriate cell in your DataGridView.