using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aptech.UI;
using System.Data.SqlClient;
using System.Media;

namespace MyQQ
{
    public partial class MainForm : Form
    {
        SbItem item;
        int index = 101;
        int faceId = 0;
        int FromId = 0;
        public static int selectId = 0;
        DataBase mydatabase = new DataBase();
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Friends();
            ShowSkin();
        }

        //显示皮肤的方法
        public void ShowSkin()
        {
            int i = 0;
            string sql = string.Format("select skinId from Users where Id={0}", UserHelper.Loginld);
            try
            {
                SqlDataReader dataReader=mydatabase.GetDataReader(sql);
                if (dataReader.Read())
                {
                    i = Convert.ToInt32(dataReader["skinId"]);
                }
                dataReader.Close();
                if (i == 1)
                {
                    this.skinEngine.SkinFile = "Wave.ssk";
                }
                else if (i == 2)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 3)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 4)
                {
                    this.skinEngine.SkinFile = "SportsBlack.ssk";
                }
                else if (i == 5)
                {
                    this.skinEngine.SkinFile = "SportsBlue.ssk";
                }
                else if (i == 6)
                {
                    this.skinEngine.SkinFile = "SportsCyan.ssk";
                }
                else if (i == 7)
                {
                    this.skinEngine.SkinFile = "SportsGreen.ssk";
                }
                else
                {
                    this.skinEngine.SkinFile = "MP10.ssk";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }

        //弹出查找好友框
        private void tsbAdd_Click(object sender, EventArgs e)
        {
            SearchFriendForm search = new SearchFriendForm();

            search.Show();
        }

        //运用Time控件循环扫描数据库
        private void timer1_Tick(object sender, EventArgs e)
        {
            int count = 0;
            string sql = string.Format("select count(MessageState) from Messages where MessageState=0 and MessageTypeId=1");
            try
            {
                count = (int)mydatabase.GetScalar(sql);
                if (count >= 1)
                {
                    tmrPicture.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        
        }

        //获得图像索引
        public void picture(int index)
        {
            pcPicture.Image = imgFace.Images[index];
        }

        //有数据时图像闪烁的时间控件
        private void timer2_Tick(object sender, EventArgs e)
        {
            string nickName = null;
            string sql = string.Format("select count(*) from Messages where MessageTypeId=1 and MessageState=0 and ToUserId={0}", Convert.ToInt32(UserHelper.Loginld));
            
            try
            {
                int num = (int)mydatabase.GetScalar(sql);

                if (num > 0 )
                {
                    sql = string.Format("select M.FromUserId,U.FaceId,U.NickName from Messages as M inner join Users as U on M.FromUserId=U.Id where M.MessageTypeId=1 and  M.MessageState=0 and M.ToUserId={0} ", Convert.ToInt32(UserHelper.Loginld));
                  
                    SqlDataReader rder = mydatabase.GetDataReader(sql);
                    if (rder.Read())
                    {
                        nickName = rder["NickName"].ToString();
                        FromId = Convert.ToInt32(rder["FromUserId"]);
                        if (rder["FaceId"] is DBNull)
                        {
                            faceId = 0;
                        }
                        else
                        {
                            faceId = Convert.ToInt32(rder["FaceId"]);
                        }

                    }
                    rder.Close();
                    //循环查询不同分组项
                    for (int i = 0; i < sbFriends.Groups.Count; i++)
                    {
                        //循环查询分组项的列表
                        for (int j = 0; j < sbFriends.Groups[i].Items.Count; j++)
                        {
                            //发信息的人与分组项的列表对号
                            if (FromId == Convert.ToInt32(sbFriends.Groups[i].Items[j].Tag))
                            {                              
                                sbFriends.Groups[i].Items[j].ImageIndex = sbFriends.Groups[i].Items[j].ImageIndex < 101 ? 101 : faceId;
                                sbFriends.Invalidate(); 
                                sbFriends.VisibleGroup = sbFriends.Groups[i];
                            }
                        }
                    }
                    SoundPlayer player = new SoundPlayer("system.wav");
                    player.Play();
                    if (!HasShowUser(FromId))
                    {
                        UpdateStranger(FromId);

                        SoundPlayer player1 = new SoundPlayer("msg.wav");

                        player1.Play();
                    }
                }

                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
          
        }
        /// <summary>
        /// 判断发消息的人是否在列表中
        /// </summary>        
        public bool HasShowUser(int FromId)
        {
            bool find = false; 
            for (int i = 0; i < 6; i++)
            {
                for (int j = 0; j < sbFriends.Groups[i].Items.Count; j++)
                {
                    if (Convert.ToInt32(sbFriends.Groups[i].Items[j].Tag) == FromId)
                    {
                        find = true;
                    }
                }
            }
            return find;
        }

        /// <summary>
        /// 更新陌生人列表
        /// </summary>        
        private void UpdateStranger(int FromId)
        {
            string sql = string.Format("select NickName, FaceId from Users where Id={0}", FromId);
            try
            {
                SqlDataReader dataReader=mydatabase.GetDataReader(sql);
                if (dataReader.Read())
                {
                    if (dataReader["FaceId"] is DBNull)
                    {
                       item = new SbItem((string)dataReader["NickName"],0);
                    }
                    else 
                    {
                        item = new SbItem((string)dataReader["NickName"], (int)dataReader["FaceId"]);
                    }
                    item.Tag = this.FromId;
                    sbFriends.Groups[5].Items.Add(item);
                }
                sbFriends.VisibleGroup = sbFriends.Groups[5];
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
       
        }

        //点击好友弹出聊天框
        private void sbFriends_ItemDoubleClick(SbItemEventArgs e)
        {
            ChatForm from = new ChatForm();
            from.friendId = Convert.ToInt32(e.Item.Tag);
            from.Show();
        }
        //弹出系统信息框
        private void tsbMessage_Click(object sender, EventArgs e)
        {
            string sql = string.Format("select count(*) from Messages where MessageTypeId=2 and MessageState=0 and ToUserId={0}",Convert.ToInt32(UserHelper.Loginld));

            int count = (int)mydatabase.GetScalar(sql);
            if (count > 0)
            {
                RequestForm requestion = new RequestForm();

                requestion.Show();
            }
        }

        //编辑个人信息事件
        private void tsbMyQQ_Click(object sender, EventArgs e)
        {
            PersonalInForm person = new PersonalInForm();
            person.Show();
        }

        //运用事件控件循环读取数据库是否有未读信息
        private void timer3_Tick(object sender, EventArgs e)
        {
            int count = 0;
            string sql = string.Format("select count(MessageState) from Messages where MessageState=0 and MessageTypeId=2 and ToUserId={0}", UserHelper.Loginld);
            try
            {
                count = (int)mydatabase.GetScalar(sql);
                if (count >= 1)
                {
                    if (index < imgFace.Images.Count - 1)
                    {
                        index++;
                    }
                    else
                    {
                        index = 101;
                    }
                    tsbMessage.Image = imgFace.Images[index];
                    SoundPlayer player = new SoundPlayer("system.wav");
                    player.Play();
                }
                else 
                {
                    tsbMessage.Image = imgFace.Images[102];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        
        }

        //关闭MyQQ运用程序 
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            DialogResult result = MessageBox.Show("您将要退出QQ程序!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            if (result == DialogResult.OK)
            {
                string sql2 = string.Format("Update Users set UserState=2 where Id={0}", Convert.ToInt32(UserHelper.Loginld));
                int result2 = mydatabase.ExecuteSQL(sql2);
                Application.Exit();
            }
        }

        //删除好友
        private void tsmDelet_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("你确定永久删除好友吗？", "删除好友提示！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

                if (result == DialogResult.OK)
                {
                    string sql = string.Format("delete from Friends where HostId={0} and FriendId={1}", UserHelper.Loginld, Convert.ToInt32(sbFriends.SeletedItem.Tag));

                    int result1 = mydatabase.ExecuteSQL(sql);
                }
            }
            catch
            {
                string message = string.Format("删除好友失败，稍后再试！！！");

                MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
         
        }

        //把大图像变为小图像
        private void tsmSmall_Click(object sender, EventArgs e)
        {
            sbFriends.View = SbView.SmallIcon;
            tsmBig.Visible = true;
            tsmSmall.Visible = false;
        }

        //小图像变为大图像
        private void tsmBig_Click(object sender, EventArgs e)
        {
            sbFriends.View = SbView.LargeIcon;
            tsmBig.Visible = false;

            tsmSmall.Visible = true;
        }

        //好友在陌生人中，将它添加为好友事件
        private void tsmAddFriend_Click(object sender, EventArgs e)
        {
            if (sbFriends.SeletedItem != null)
            {
                if (!HasShowUser(FromId))
                {
                    MessageBox.Show("他已经是你的好友！！！", "提示");
                }
                else
                {
                    try
                    {
                        sbFriends.Groups[5].Items.Remove(item);
                        int friendId = Convert.ToInt32(sbFriends.SeletedItem.Tag.ToString().Substring(0, 5));
                        string sql = string.Format("insert into Friends (HostId,FriendId,FriendGroup) values ({0},{1},0)", UserHelper.Loginld, friendId);

                        mydatabase.ExecuteSQL(sql);

                        sbFriends.Groups[0].Items.Add(item);
                    }
                    catch
                    {   
                        string message = "添加好友失败，请稍后再试！！！";

                        MessageBox.Show(message, "提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                    }
                }
            }
        }
        //起到刷新效果的时间控件处理事件
        private void trFriends_Tick(object sender, EventArgs e)
        {
            sbFriends.Groups.Clear();
            Friends();
        }

        /// <summary>
        /// 在好友列表显示好友的方法
        /// </summary>
        public void Friends()
        {
            Text = UserHelper.Loginld;
            notifyIcon1.Text = UserHelper.Loginld;
            lblId.Text = "(" + UserHelper.Loginld + ")";
            this.sbFriends.AddGroup("我的好友");
            this.sbFriends.AddGroup("我的同学");
            this.sbFriends.AddGroup("我的亲人");
            this.sbFriends.AddGroup("我的情人");
            this.sbFriends.AddGroup("不认识的人");
            this.sbFriends.AddGroup("陌生人");
            string sql = string.Format("select NickName from Users where Id={0}", Convert.ToInt32(UserHelper.Loginld));
            try
            {
                SqlDataReader dataReade = mydatabase.GetDataReader(sql);
                if (dataReade.Read())
                {
                    lblNickName.Text = (string)dataReade["NickName"];
                }
                dataReade.Close();
                sql = string.Format("select NickName,FaceId,FriendId,FriendGroup,Friendbeizhu from Users as U inner join Friends as F on U.Id=F.FriendId where F.HostId={0} and UserState=1", Convert.ToInt32(UserHelper.Loginld));

                SqlDataReader Reader = mydatabase.GetDataReader(sql);
                while (Reader.Read())
                {
                    if (!(Reader["FaceId"] is DBNull))
                    {
                        if (Reader["Friendbeizhu"] is DBNull)
                        {
                            item = new SbItem(Reader["NickName"].ToString(), Convert.ToInt32(Reader["FaceId"]));
                        }
                        else 
                        {
                            item = new SbItem(Reader["Friendbeizhu"].ToString(), Convert.ToInt32(Reader["FaceId"]));
                        }
                        item.Tag = Convert.ToInt32(Reader["FriendId"]);
                        ///SideBar中的组可以通过数组的方式访问，按照添加的顺序索引从0开始
                        ///Groups[0]表示SideBar中的第一个组，也就是“我的好友”组
                        ///向组中添加一项
                        int groups = Convert.ToInt32(Reader["FriendGroup"]);
                        this.sbFriends.Groups[groups].Items.Add(item);     //好友组
                    }
                    else
                    {
                        if (Reader["Friendbeizhu"] is DBNull)
                        {
                            item = new SbItem(Reader["NickName"].ToString(),0);
                        }
                        else
                        {
                            item = new SbItem(Reader["Friendbeizhu"].ToString(),0);
                        }

                        item = new SbItem(Reader["NickName"].ToString(), 0);

                        item.Tag = Convert.ToInt32(Reader["FriendId"]);
                        //SideBar中的组可以通过数组的方式访问，按照添加的顺序索引从0开始
                        //Groups[0]表示SideBar中的第一个组，也就是“我的好友”组
                        //向组中添加一项
                        int groups = Convert.ToInt32(Reader["FriendGroup"]);

                        this.sbFriends.Groups[groups].Items.Add(item);     //好友组
                    }
                }
                Reader.Close();
                string sql1 = string.Format("select NickName,FaceId,FriendId,FriendGroup,Friendbeizhu from Users as U inner join Friends as F on U.Id=F.FriendId where F.HostId={0} and UserState!=1", Convert.ToInt32(UserHelper.Loginld));

                SqlDataReader Reader1 = mydatabase.GetDataReader(sql1);
                if (Reader1.HasRows)
                {
                    while (Reader1.Read())
                    {
                        if (Reader1["Friendbeizhu"] is DBNull)
                        {
                            item = new SbItem(Reader1["NickName"].ToString(), 73);
                        }
                        else
                        {
                            item = new SbItem(Reader1["Friendbeizhu"].ToString(),73);
                        }

                        item.Tag = Convert.ToInt32(Reader1["FriendId"]);

                        ///SideBar中的组可以通过数组的方式访问，按照添加的顺序索引从0开始
                        ///Groups[0]表示SideBar中的第一个组，也就是“我的好友”组
                        ///向组中添加一项
                        int groups = Convert.ToInt32(Reader1["FriendGroup"]);

                        this.sbFriends.Groups[groups].Items.Add(item);     //好友组
                    }
                    Reader1.Close();
                }
                sql = string.Format("select FaceId,UserState from Users where Id={0}", Convert.ToInt32(UserHelper.Loginld));
                SqlDataReader dataRead = mydatabase.GetDataReader(sql);
                while (dataRead.Read())
                {
                    if (dataRead["FaceId"] is DBNull)
                    {
                        pcPicture.Image = imgFace.Images[0];
                    }
                    else
                    {
                        pcPicture.Image = imgFace.Images[(int)dataRead["FaceId"]];
                    }
                    if (Convert.ToInt32(dataRead["UserState"]) == 1)
                    {
                        Text += " [上线]";
                    }
                    else
                    {
                        Text += " [隐身]";
                    }
                }
                dataRead.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //把皮肤颜色变透明
        private void tsmiBianQian_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.4; 

            tsmiBianQian.Visible = false;

            tsmiDop.Visible = true;
        }

        //把皮肤颜色变不透明
        private void tsmiDop_Click(object sender, EventArgs e)
        {
            this.Opacity = 1.8;

            tsmiBianQian.Visible = true;

            tsmiDop.Visible = false;
        }

        //更换皮肤
        private void tsmiSport_Click(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
            string sql = string.Format("Update Users set skinId={0} where Id={1}", i, UserHelper.Loginld);

            int result = mydatabase.ExecuteSQL(sql);
            if (result > 0)
            {
                if (i == 1)
                {
                    this.skinEngine.SkinFile = "Wave.ssk";
                }
                else if (i == 2)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 3)
                {
                    this.skinEngine.SkinFile = "WaveColor1.ssk";
                }
                else if (i == 4)
                {
                    this.skinEngine.SkinFile = "SportsBlack.ssk";
                }
                else if (i == 5)
                {
                    this.skinEngine.SkinFile = "SportsBlue.ssk";
                }
                else if (i == 6)
                {
                    this.skinEngine.SkinFile = "SportsCyan.ssk";
                }
                else if (i == 7)
                {
                    this.skinEngine.SkinFile = "SportsGreen.ssk";
                }
                else
                {
                    this.skinEngine.SkinFile = "MP10.ssk";
                }
                MessageBox.Show("恭喜你更新成功！", "更新提示");
            }
        }

        //查看好友信息
        private void SeePersonInform_Click(object sender, EventArgs e)
        {
           
            try
            {
                DialogResult result = MessageBox.Show("你确定要查看好友信息吗", "提示", MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    pnlPerson.Visible = true;
                    sbFriends.Visible = false;
                    int start = 0;
                    int Blood = 0;
                    int friendsId = Convert.ToInt32(sbFriends.SeletedItem.Tag.ToString().Substring(0, 5));
                    string sql = string.Format("select NickName,FaceId,Sex,Age,Name,StarId,BloodTypeId from Users where Id={0}", friendsId);

                    SqlDataReader dataReader = mydatabase.GetDataReader(sql);
                    //运用SqlDataReader读取数据
                    if (dataReader.Read())
                    {
                        if (dataReader["FaceId"] is DBNull)
                        {
                            picFriends.Image = imgFace.Images[0];
                        }
                        else
                        {
                            picFriends.Image = imgFace.Images[Convert.ToInt32(dataReader["FaceId"])];
                        }
                        lblNum.Text = "(" + friendsId + ")";
                        txtNName.Text = (string)dataReader["NickName"];
                        txtSes.Text = (string)dataReader["Sex"];
                        txtAges.Text = dataReader["Age"].ToString();
                        if (dataReader["Name"] is DBNull)
                        {
                            txtNames.Text = "";
                        }
                        else
                        {
                            txtNames.Text = (string)dataReader["Name"];
                        }
                        if (!(dataReader["StarId"] is DBNull))
                        {
                            start = Convert.ToInt32(dataReader["StarId"]);
                        }
                        else
                        {
                            start = 0;
                        }
                        if (!(dataReader["BloodTypeId"] is DBNull))
                        {
                            Blood = Convert.ToInt32(dataReader["BloodTypeId"]);
                        }
                        else
                        {
                            Blood = 0;
                        }
                    }
                    dataReader.Close();
                    if (start != 0)
                    {
                        string sql2 = string.Format("select Star from Star where Id={0}", start);
                        SqlDataReader detaReade = mydatabase.GetDataReader(sql2);
                        if (detaReade.Read())
                        {
                            txtStars.Text = (string)detaReade["Star"];
                        }
                    }
                    else
                    {
                        txtStars.Text = "";
                    }
                    if (Blood != 0)
                    {
                        string sql3 = string.Format("select BloodType from BloodType where Id={0}", Blood);

                        SqlDataReader detaReader = mydatabase.GetDataReader(sql3);
                        if (detaReader.Read())
                        {
                            txtBlood.Text = (string)detaReader["BloodType"];
                        }

                    }
                    else
                    {
                        txtBlood.Text = "";
                    }
                }
            }
            catch
            {
                string message = "查看好友信息失败，请稍后再试！！！";

                MessageBox.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        //基本信息返回处理事件
        private void btnReturn_Click(object sender, EventArgs e)
        {
            pnlPerson.Visible = false;

            sbFriends.Visible = true;
        }

        //主窗体已图标在任务栏显示
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            // 当主窗体的状态是最小化在任务栏显示时，把主窗体还原
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
            else
            {
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }

        //改变在线状态的事件
        private void tsmiStations_Click(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
            string sql2 = string.Format("Update Users set UserState={0} where Id={1}", i, Convert.ToInt32(UserHelper.Loginld));

            int result=mydatabase.ExecuteSQL(sql2);
        }

        //右键菜单下线按钮事件
        private void tsmiStation2_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("你确定要下线吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (result == DialogResult.OK)
            {
                string sql2 = string.Format("Update Users set UserState=2 where Id={0}", Convert.ToInt32(UserHelper.Loginld));

                int result2 = mydatabase.ExecuteSQL(sql2);
                Application.Exit();
            }
        }

        //鼠标单击窗体时,窗体隐身的事件
        private void MainForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.Location.X >= 760 && this.Location.Y >= 40)
            {
                this.Location = new Point(1020, 40);
            }
            else if ((this.Location.X < 760 && this.Location.Y < 40) || this.Location.X < 760)
            {
                this.Location = new Point(760,-560);
            }
            else
            {
                this.Location = new Point(760, 40);
            }
        }

        //当鼠标进入窗体时发生
        private void MainForm_MouseEnter(object sender, EventArgs e)
        {
            if (this.Location.X == 1020 && this.Location.Y == 40)
            {
                this.Location = new Point(760, 40);
            }
            else if (this.Location.X == 760 && this.Location.Y == -560) 
            {
                this.Location = new Point(760, 40);
            }
        }

        /// <summary>
        /// 转移好友事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void msGroups_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("确定要转移好友吗？", "提示", MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    int j = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);
                    string sql = string.Format("update Friends set FriendGroup={0} where FriendId={1} and HostId={2}", j, Convert.ToInt32(sbFriends.SeletedItem.Tag), Convert.ToInt32(UserHelper.Loginld));

                    int result1 = mydatabase.ExecuteSQL(sql);
                }
            }
            catch
            {
                string message = "你暂时不能移动好友，请稍后再试！！！";

                MessageBox.Show(message, "提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }

        /// <summary>
        /// 修改好友备注事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBeizhu_Click(object sender, EventArgs e)
        {
            try
            {

                DialogResult result = MessageBox.Show("确定要修改好友备注吗？", "提示", MessageBoxButtons.OKCancel);

                if (result == DialogResult.OK)
                {
                    selectId = Convert.ToInt32(sbFriends.SeletedItem.Tag);

                    BeizhuForm beizhu = new BeizhuForm();

                    beizhu.ShowDialog();
                }
            }
            catch 
            {
                MessageBox.Show("你暂时不能修改好友备注！！！", "提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }

        /// <summary>
        /// 查询好友是否发送窗口抖动时间控件的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick_1(object sender, EventArgs e)
        {

            int fromId = 0;
            string sql = string.Format("select FromUserId from Messages where ToUserId={0} and MessageTypeId=3 and MessageState=0", Convert.ToInt32(UserHelper.Loginld));

            SqlDataReader data = mydatabase.GetDataReader(sql);
            while (data.Read()) 
            {
                fromId = Convert.ToInt32(data["FromUserId"]);
            }

            data.Close();

            string sql1 = string.Format("select MessageX,MessageY from Messages where FromUserId={0} and ToUserId={1} and MessageTypeId=3 and MessageState=0", fromId, Convert.ToInt32(UserHelper.Loginld));

            SqlDataReader datareader = mydatabase.GetDataReader(sql1);
            if (datareader.HasRows)
            {
                if (datareader.Read())
                {
                    if (!(datareader["MessageX"] is DBNull) && !(datareader["MessageY"] is DBNull))
                    {

                        datareader.Close();
                        ChatForm from = new ChatForm();
                        from.friendId = fromId;

                        from.Show();
                    }
                }
                datareader.Close();
            }       
        }
    }
}