我正在创建一个聊天应用程序,我想以Bold显示名称。首次加载表单时,我使用这些代码行在控件上显示来自数据库的历史对话,RichTextBox
并且我想以粗体显示名称:
这是使这成为可能的所有代码:
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); }
这些是无法按预期工作的代码行:
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);
}
编辑:
dr.GetValue(1).ToString()
保留用户
dr.GetValue(6).ToString()
的全名 保留消息
上面代码的问题是它仅以粗体显示名字,但其他行不受影响。查看图片
有人可以告诉我代码不起作用的原因。我无法弄清楚错误在哪里。
谢谢