I’m creating a chat application and I want to display names in Bold . When the form is first load, I display the History conversation from database on a RichTextBox control using these lines of code and i want to display the name in Bold :
Here’s all the code to make this possible :
string strProvider = "Data Source=" + srv_host + ";Database=" + srv_db + ";User ID=" + srv_user + ";Password=" + srv_pass;
MySqlConnection myConn = new MySqlConnection(strProvider);
try
{
myConn.Open();
string strCmd = "SELECT * FROM comments WHERE task_id=@task_id AND ((from_usr=@from AND to_usr=@to) OR (from_usr=@to AND to_usr=@from)) ORDER BY at_time ASC";
MySqlCommand myCmd = new MySqlCommand(strCmd, myConn);
myCmd.Parameters.AddWithValue("from", frm_usr);
myCmd.Parameters.AddWithValue("to", to_usr);
myCmd.Parameters.AddWithValue("task_id", tid);
myCmd.ExecuteNonQuery(); // execute now
MySqlDataReader dr = myCmd.ExecuteReader();
while (dr.Read())
{
string text = dr.GetValue(1).ToString() + ": " + dr.GetValue(6) + Environment.NewLine;
richTextBox1.AppendText(text);
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = dr.GetValue(1).ToString().Length;
richTextBox1.SelectionFont = new Font(richTextBox1.Font,FontStyle.Bold);
}
myConn.Dispose();
}
catch (Exception E) { MessageBox.Show(E.Message); }
And these are the lines of code that doesn’t work as expected :
while (dr.Read())
{
string text = dr.GetValue(1).ToString() + ": " + dr.GetValue(6) + Environment.NewLine;
richTextBox1.AppendText(text);
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = dr.GetValue(1).ToString().Length;
richTextBox1.SelectionFont = new Font(richTextBox1.Font,FontStyle.Bold);
}
Edit:
dr.GetValue(1).ToString() Holds tha full name of user
dr.GetValue(6).ToString() Hold the message
The problem with code above is that it displays only the first name in Bold but other lines are not affected. See the image 
Could some one please tell me the reason why the code isn’t working. I couldn’t figure out where is the error.
Thank-you
The problem you are having here is that
richTextBox1.SelectionStartis always zero, meaning that the formatting will only ever be applied to the first line in the text box.Try setting this to
richTextBox1.SelectionStart = richTextBox1.TextLength.Edit:
Try setting it to
Edit 2:
I think the Invalid Argument thing is caused by the use of
Environment.NewLine. If I use instead"\n", the code works fine. The problem is thatEnvironment.NewLineis of course\r\non Windows, yet therichtextBox1seems to be ignoring the\r. This results inrichTextBox1.TextLength - text.Lengthbeing -1 in the first iteration.