I am setting up an application for a travel guide using Windows Forms in Visual Studio.
In some forms there is a richTextBox with contact info and description for places to eat. In the upper right corner, there is a button with an export icon, so that the user will be able to export info to a txt file. What I want to do, is: if the user has not highlighted any text when he presses the button, all the contents of the textBox will be exported. If on the other hand he has highlighted some text, then only the selected text will be exported.Here is the code:
private void Button4_Click(object sender, EventArgs e)
{
SaveFileDialog fd = new SaveFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
string FileName = fd.FileName;
fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
byte[] bytext;
if(richTextBox1.SelectedText.Length == 0)
{
bytext = System.Text.Encoding.UTF8.GetBytes(richTextBox1.Text);
}
else
{
bytext = System.Text.Encoding.UTF8.GetBytes(richTextBox1.SelectedText);
}
fs.Write(bytext, 0, bytext.Length);
fs.Close();
}
The code works as expected, the only problem is: when the user highlights some text, exports it, and then, with no text highlighted, presses the export button again. Then, instead of exporting the whole text, only the previously highlighted text is exported. So I want to reset the value of the SelectedText to an empty string.I tried richTextBox1.Selected.Text = ""; but it doesn't work. How can I do that?