最近做小QQ;聊天界面用lable输入不到好多,用了textbox,因为需要换行,用了\r\n
代码如下(关闭窗口时 在Application.Run(new LoginForm());报错:无法绑定由多个部分组成的标识符 "System.Data.SqlClient.SqlConnection"。):         public int friendId;     // 当前聊天的好友号码
        public string nickName;  // 当前聊天的好友昵称
        public int faceId;       // 当前聊天的好友头像Id        
        string allMessage=;      //所有的信息
        string userNickname;    //用户昵称
        SoundPlayer player = new SoundPlayer("msg.wav");     //声音设置        public ChatForm()
        {
            InitializeComponent();
        }
            private void ChatForm_Load(object sender, EventArgs e)
        {
            DBHelper.conn.Open();
            string sql2 = string.Format("select *from users where id={0}",friendId);
            SqlCommand cmd2 = new SqlCommand(sql2, DBHelper.conn);
            SqlDataReader dr2 = cmd2.ExecuteReader();
            if (dr2.Read())
            {
                string NameShow = string.Format("{0}({1})", dr2["nickname"],friendId);
                faceId = (int)dr2["faceid"];
                lblFriend .Text = NameShow;
                picFace.Image = ilFaces .Images[faceId];
                nickName = dr2["nickname"].ToString();
            }
            dr2.Close();
            this.Text = string.Format("与{0}聊天中", nickName);// 设置窗体标题
            picFace.Image = ilFaces.Images[faceId];// 设置窗体顶部显示的好友信息
            lblFriend.Text = string.Format("{0}({1})", nickName, friendId);
            DBHelper.conn.Close();
            string sql = string.Format("insert into openchat values({0},{1})",UserHelper.Loginid,friendId);
            AddDel(sql);
            userNickname = userNick();
            ShowMessage();// 读取所有的未读消息,显示在窗体中
            tmrMessages.Start();
            txtChat.Focus();
        }
        public string userNick()//得到用户的昵称方法
        {
            string sql = string.Format("select * from users where id={0}", UserHelper.Loginid);
            DBHelper.conn.Open();
            SqlCommand cmd = new SqlCommand(sql,DBHelper.conn);
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                userNickname = reader["nickname"].ToString();
            }
            reader.Close();
            DBHelper.conn.Close();
            return userNickname;
        }
        private void btnClose_Click(object sender, EventArgs e) // 关闭窗体
        {
            try
            {
                string sql = "delete from openchat where userid=" + DBHelper.conn + " and friendchatid=" + friendId;
                AddDel(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
            this.Close();
        }
        private static void AddDel(string sql)
        {
            DBHelper.conn.Open();
            SqlCommand cmd = new SqlCommand(sql, DBHelper.conn);
            cmd.ExecuteNonQuery();
            DBHelper.conn.Close();
        }       
        private void btnSend_Click(object sender, EventArgs e)// 发送消息
        {
            if (txtChat.Text.Trim() == "") // 不能发送空消息
            {
                MessageBox.Show("不能发送空消息!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (txtChat.Text.Trim().Length > 50)
            {
                MessageBox.Show("消息内容过长,请分为几条发送!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else            {
                    int result = -1; // 表示操作数据库的结果
                string sql = string.Format(
                    "insert into  Messages (FromUserId, ToUserId, Message, MessageTypeId, MessageState) values ({0},{1},'{2}',{3},{4})",
                    UserHelper.Loginid, friendId, txtChat.Text.Trim(), 1, 0);
                try
                {
                               SqlCommand command = new SqlCommand(sql, DBHelper.conn);
                    DBHelper.conn.Open();
                    result = command.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    DBHelper.conn.Close();
                }
                if (result != 1)
                {
                    MessageBox.Show("服务器出现意外错误!", "抱歉", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                allMessage += "\r\n" +userNickname+"   "+DateTime.Now.ToShortDateString()+" "+DateTime.Now.ToShortTimeString()+"\r\n  "+ txtChat.Text;
                txtMessage.Text = allMessage;
                txtChat.Text = "";  // 输入消息清空
                txtChat.Focus();
            }
        }
          private void ShowMessage()
        {
            string messageIdsString = "";  // 消息的Id组成的字符串
            string message;         // 消息内容
            string messageTime;     // 消息发出的时间
            string sql = string.Format(
                "select Id, Message,MessageTime from Messages where FromUserId={0} and ToUserId={1} and MessageTypeId=1 and MessageState=0",
                friendId, UserHelper.Loginid);
            try
            {
                DBHelper.conn.Open();
                SqlCommand command = new SqlCommand(sql, DBHelper.conn);
                SqlDataReader reader = command.ExecuteReader();
                 while (reader.Read())
                {
                    messageIdsString += Convert.ToString(reader["Id"]) + "_";
                    message = Convert.ToString(reader["Message"]);
                    messageTime = Convert.ToDateTime(reader["MessageTime"]).ToString(); // 转换为日期类型,告诉学员
                    allMessage+=string.Format("\r\n{0}  {1}\r\n  {2}", nickName, messageTime, message);
                    txtMessage.Text = allMessage;
                    player.Play();
                }
                reader.Close();
           }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.conn.Close();
            }
            // 把显示出的消息置为已读
            if (messageIdsString.Length >= 1)
            {
                messageIdsString.Remove(messageIdsString.Length - 1);
                          SetMessageRead(messageIdsString, '_');
            }
        }
        private void SetMessageRead(string messageIdsString, char separator)  /// 把显示出的消息置为已读        {
            string[] messageIds = messageIdsString.Split(separator);     // 分割出每个消息Id
            
            string sql = "update Messages set MessageState=1 where Id="; // 更新状态的SQL语句的固定部分
            string updateSql;  // 执行的SQL语句
            try
            {
                    SqlCommand command = new SqlCommand();     // 创建Command对象
                    command.Connection = DBHelper.conn;  // 指定数据库连接
                    DBHelper.conn.Open();                // 打开数据库连接
                    foreach (string id in messageIds)
                    {
                        if (id != "")
                        {
                            updateSql = sql + id;              // 补充完整的SQL语句
                            command.CommandText = updateSql;   // 指定要执行的SQL语句
                            int result = command.ExecuteNonQuery();  // 执行命令
                        }
                    }
             }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                DBHelper.conn.Close();
            }
        }     }
}

解决方案 »

  1.   

    string sql = "delete from openchat where userid=" + DBHelper.conn + " and friendchatid=" + friendId; DBHelper.conn 应该是你的连接,所以你这个Sql语句出错string userId=""; //你获取到的UserId,不管理是TextBox或者其它,而且建议加上引号
    string sql = "delete from openchat where userid='" + userId + "' and friendchatid='" + friendId+"'"; 
      

  2.   

    三楼正解,刚刚我也遇到这个问题了,百度了一下,解决了,那就做个好人好事,告诉楼主一声:是你的sql语句引发的异常,只要将userid等参数都加上单引号就ok了,注意:就算数据库中存的是int类型的,也要加引号。