QQ项目之五查找和添加好友

举报
tea_year 发表于 2021/12/30 01:24:09 2021/12/30
【摘要】 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Syste...

  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Data.SqlClient; //引用命名空间
  9. namespace MYQQ
  10. {
  11. /// <summary>
  12. /// 查找和添加好友窗体;注意是周末大家要实现的大招,难度中难~.~
  13. /// </summary>
  14. //**********************第1步:在类中声明2个成员变量,用来存取数据*************************
  15. public partial class SearchFriendForm : Form
  16. {
  17. private DataSet dataSet; // 数据集
  18. private SqlDataAdapter dataAdapter; // 数据适配器
  19. //*********************第1步实现完毕********************************************************
  20. public SearchFriendForm()
  21. {
  22. InitializeComponent();
  23. }
  24. #region 第2步,窗体加载代码,填充数据集;
  25. private void SearchFriendForm_Load(object sender, EventArgs e)
  26. {
  27. // 实例化数据集和数据适配器并填充,断点、try块捕获异常;
  28. try
  29. {
  30. string sql = "SELECT Id, NickName, Age, Sex FROM Users"; //定义查询语句,如果不设计datagridView控件,则使用别名实现!
  31. dataAdapter = new SqlDataAdapter(sql, DBHelper.conn); //实现小货车new
  32. dataSet = new DataSet("MyQQ"); //临时仓库MyQQ
  33. dataAdapter.Fill(dataSet, "Users"); //临时表Users
  34. // 指定DataGridView的数据源
  35. dgvBasicResult.DataSource = dataSet.Tables["Users"]; //给基本数据表格(dgvBasicResult)指定数据源
  36. dgvAdvancedResult.DataSource = dataSet.Tables["Users"]; //给高级数据表格(dgvAdvancedResult)指定数据源
  37. }
  38. catch (Exception ex)
  39. {
  40. MessageBox.Show(ex.Message);
  41. }
  42. }
  43. #endregion
  44. #region 第3步 点击查找按钮时,查找符合条件的用户,p268
  45. private void btnSearch_Click(object sender, EventArgs e)
  46. {
  47. if (tabSearch.SelectedIndex == 0) // 基本查找选显卡选中
  48. { //实现,将业务逻辑的粒度进行细分;
  49. BasicallySearch(); //自定义方法,基本查找;写到类中,其他方法外,和其他方法是兄弟关系;
  50. }
  51. else // 高级查找选项卡选中
  52. {
  53. AdvancedSearch(); //自定义方法:高级查找;
  54. }
  55. }
  56. /// <summary>
  57. /// 这是基本查找方法..;需要4种sql语句;全部查找,加载时候已经实现;
  58. /// 3种;两个都不选,会有提示框;选一个ID/Nickname/
  59. /// </summary>
  60. #endregion
  61. #region 添加好友;整体框架
  62. private void btnAdd_Click(object sender, EventArgs e)
  63. {
  64. int friendshipPolicyId = -1; // 对方的好友策略
  65. int friendId = GetSelectedFriendId(); //子步骤1:获得选中的好友的Id;
  66. if (friendId == -1)// 是否有可添加的好友
  67. {
  68. MessageBox.Show("请选择一个好友!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  69. return;
  70. }
  71. else if (friendId == UserHelper.loginId)
  72. {
  73. MessageBox.Show("不能加自己为好友!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  74. return;
  75. }
  76. else if (HasAdded(friendId)) //子步骤2:确认是否需要添加(是否已经是好友了)
  77. {
  78. MessageBox.Show("对方已在你的好友列表中!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  79. return;
  80. }
  81. //上面都是无效条件,除此之外,就是可以添加好友的情况;添加好友又分几种情况呢?
  82. friendshipPolicyId = GetFriendshipPolicyId(friendId); //添加好友子步骤3,获得好友好友号码的好友策略
  83. if (friendshipPolicyId == 3) // 3表示不允许任何人添加,在S2可以使用常量或枚举
  84. {
  85. MessageBox.Show("对方不允许任何人加他为好友!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  86. return;
  87. }
  88. else if (friendshipPolicyId == 2) // 2:表示需要身份验证
  89. {
  90. int result = SendRequest(friendId); // 添加好友子步骤4:发验证消息
  91. //可以再调出来一个窗体,进行传值.
  92. if (result == 1)
  93. {
  94. MessageBox.Show("对方需要身份验证才能被加为好友,已发出请求!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  95. }
  96. else
  97. {
  98. MessageBox.Show("添加失败,请稍候再试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  99. }
  100. }
  101. else if (friendshipPolicyId == 1) // 1:表示允许任何人添加为好友
  102. {
  103. int result = AddFriend(friendId); //添加好友子步骤5: 执行添加操作
  104. if (result == 1)
  105. {
  106. MessageBox.Show("添加成功,请刷新好友列表!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  107. }
  108. else
  109. {
  110. MessageBox.Show("添加失败,请稍候再试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  111. }
  112. }
  113. }
  114. #endregion
  115. // 当切换页时,把与查找结果相关的控件都隐藏
  116. private void tabSearch_SelectedIndexChanged(object sender, EventArgs e)
  117. {
  118. pnlBaseResult.Visible = false;
  119. pnlAdvancedResult.Visible = false;
  120. btnAdd.Visible = false;
  121. btnBack.Visible = false;
  122. }
  123. // 控制精确查找选项是否可见;设置下面的隐藏可以见
  124. private void rdoNicetySearch_CheckedChanged(object sender, EventArgs e)
  125. {
  126. if (rdoNicetySearch.Checked == true)
  127. {
  128. grpBaseCondition.Visible = true; //控制精确查找面板的可见
  129. }
  130. else
  131. {
  132. grpBaseCondition.Visible = false; //不可见
  133. }
  134. }
  135. // 返回到上一步
  136. private void btnBack_Click(object sender, EventArgs e)
  137. {
  138. pnlBaseResult.Visible = false; //结果面板,隐藏
  139. pnlAdvancedResult.Visible = false; //高级查找面板,隐藏
  140. pnlBaseCondition.Visible = true; // 基本查找可见;
  141. pnlAdvancedCondition.Visible = true;//高级查找可见;
  142. btnBack.Visible = false; //上一步按钮,隐藏
  143. btnAdd.Visible = false; //添加,隐藏
  144. }
  145. // 关闭窗体
  146. private void btnClose_Click(object sender, EventArgs e)
  147. {
  148. this.Close();
  149. }
  150. #region 第4步:基本查找
  151. private void BasicallySearch()
  152. { //拼接Sql语句 // 查询语句的前半部分
  153. string sql = "SELECT Id,NickName,Age,Sex FROM Users";
  154. // 精确查找单选按钮的name:rdoNicetySearch
  155. if (rdoNicetySearch.Checked == true)
  156. {
  157. if (txtLoginId.Text.Trim() == "" && txtNickName.Text.Trim() == "")
  158. {
  159. MessageBox.Show("还没有填查询条件呢!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  160. return; //注意,只有return
  161. }
  162. // 按帐号查找
  163. else if (txtLoginId.Text.Trim() != "" && txtNickName.Text.Trim() == "")
  164. {
  165. sql += string.Format(" WHERE Id={0}", int.Parse(txtLoginId.Text.Trim()));
  166. }
  167. // 按昵称查找
  168. else if(txtNickName.Text.Trim()!="" && txtLoginId.Text.Trim()=="")
  169. {
  170. sql += string.Format(" WHERE NickName like '%{0}%'", txtNickName.Text.Trim()); //like:模糊
  171. }
  172. else{ //既然,账号和昵称必须一致;
  173. sql+=string.Format(" where Id={0} and NickName like '%{1}'",int.Parse(txtLoginId.Text.Trim()),txtNickName.Text.Trim());
  174. }
  175. }
  176. // 重新填充DataSet
  177. dataSet.Tables[0].Clear(); //清空临时库中第一个表(即Users表)的数据
  178. dataAdapter.SelectCommand.CommandText = sql; //设置小货车查询小二的命令;
  179. dataAdapter.Fill(dataSet, "Users"); //使用小货车,重新填充数据岛Users表中;
  180. // 设置控件可见的属性
  181. // 调整显示结果的panel的位置,让它和显示条件的Panel的位置相同
  182. pnlBaseResult.Location = pnlBaseCondition.Location;
  183. // 使显示结果的panel可见
  184. pnlBaseResult.Visible = true;
  185. btnAdd.Visible = true;  //“加为好友”按钮可见
  186. btnBack.Visible = true; //“上一步”按钮可见
  187. }
  188. #endregion
  189. //1.声明2个成员变量;
  190. //2.窗体加载代码;
  191. //3.点击查找,出现两种情况;
  192. //4.基本查找;
  193. //5.高级查找;
  194. #region 第5步 高级查找
  195. private void AdvancedSearch()
  196. {
  197. string sql = "SELECT Id,NickName,Age,Sex FROM Users ";
  198. string ageCondition = ""; // 年龄条件
  199. string sexCondition = cboSex.Text; // 性别条件
  200. // 确定年龄的范围
  201. switch (cboAge.SelectedIndex) //选择项索引,从0开始;0:不限;
  202. {
  203. case 1:
  204. ageCondition = " Age>=0 AND Age<10";
  205. break;
  206. case 2:
  207. ageCondition = " Age>=10 AND Age<20";
  208. break;
  209. case 3:
  210. ageCondition = " Age>=20 AND Age<30";
  211. break;
  212. case 4:
  213. ageCondition = " Age>=30 AND Age<40";
  214. break;
  215. case 5:
  216. ageCondition = " Age>=40 AND Age<50";
  217. break;
  218. case 6:
  219. ageCondition = " Age>=50";
  220. break;
  221. default:
  222. ageCondition = "";
  223. break;
  224. }
  225. if (ageCondition == "" && sexCondition == "")
  226. {
  227. MessageBox.Show("还没有选择查询条件呢!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  228. return;
  229. }
  230. else
  231. {//否则,有3种情况。
  232. if (ageCondition != "" && sexCondition == "") //只有年龄
  233. {
  234. sql += string.Format(" WHERE {0}", ageCondition);
  235. }
  236. else if (ageCondition == "" && sexCondition != "") //只有性别
  237. {
  238. sql += string.Format(" WHERE Sex='{0}'", sexCondition);
  239. }
  240. else
  241. { //两个条件都有
  242. sql += string.Format(" WHERE {0} AND Sex='{1}'", ageCondition, sexCondition);
  243. }
  244. }
  245. // 开始查找
  246. dataAdapter.SelectCommand.CommandText = sql;
  247. dataSet.Tables[0].Clear();
  248. dataAdapter.Fill(dataSet, "Users");
  249. // 设置控件的属性
  250. pnlAdvancedResult.Location = pnlAdvancedCondition.Location;
  251. pnlAdvancedResult.Visible = true;
  252. btnAdd.Visible = true;
  253. btnBack.Visible = true;
  254. }
  255. #endregion
  256. /// <summary>
  257. /// 添加好友子步骤1:获得选中的好友的Id
  258. /// </summary>
  259. private int GetSelectedFriendId()
  260. {
  261. int friendId = -1; // 好友的号码
  262. if (tabSearch.SelectedIndex == 0) // 基本查找
  263. {
  264. // 没有选中任何一行
  265. if (dgvBasicResult.SelectedRows.Count == 0)
  266. {
  267. MessageBox.Show("请选择一个好友!", "操作", MessageBoxButtons.OK, MessageBoxIcon.Information);
  268. }
  269. // 确保第一个单元格有值;Cells:单元格;
  270. else if(dgvBasicResult.SelectedRows[0].Cells[0] != null)
  271. {
  272. // 获得DataGridView中选中的行的第一个单元格的值
  273. friendId = int.Parse(dgvBasicResult.SelectedRows[0].Cells[0].Value.ToString());
  274. }
  275. }
  276. // 高级查找
  277. else
  278. {
  279. if (dgvAdvancedResult.SelectedRows.Count == 0)
  280. {
  281. MessageBox.Show("请选择一个好友!", "操作", MessageBoxButtons.OK, MessageBoxIcon.Information);
  282. }
  283. else if (dgvAdvancedResult.SelectedRows[0].Cells[0] != null)
  284. {
  285. friendId = int.Parse(dgvAdvancedResult.SelectedRows[0].Cells[0].Value.ToString());
  286. }
  287. }
  288. return friendId; //切记:返回好友ID
  289. }
  290. /// <summary>
  291. /// 确认对方能否被加为好友
  292. /// </summary>
  293. private int GetFriendshipPolicyId(int friendId) //好友号码,作为参数过去10009
  294. {
  295. int friendshipPolicyId = 1; // 好友策略
  296. string sql = "SELECT FriendshipPolicyId FROM Users WHERE Id=" + friendId;
  297. try
  298. {
  299. SqlCommand command = new SqlCommand(sql, DBHelper.conn);
  300. DBHelper.conn.Open();
  301. friendshipPolicyId = Convert.ToInt32(command.ExecuteScalar());
  302. }
  303. catch (Exception ex)
  304. {
  305. Console.WriteLine(ex.Message);
  306. }
  307. finally
  308. {
  309. DBHelper.conn.Close();
  310. }
  311. return friendshipPolicyId;
  312. }
  313. //*********************************子步骤3结束了*************************
  314. /// <summary>
  315. /// 添加好友子步骤2
  316. /// </summary>
  317. private bool HasAdded(int friendId) //把刚才获得的好友号码,作为参数,给传过来.
  318. {
  319. int result = 0; // 查找结果
  320. bool returnValue; // 返回值
  321. string sql = string.Format("SELECT COUNT(*) FROM Friends WHERE HostId={0} AND FriendId={1}",UserHelper.loginId, friendId);
  322. try
  323. {
  324. SqlCommand command = new SqlCommand(sql, DBHelper.conn);
  325. DBHelper.conn.Open();
  326. result = Convert.ToInt32(command.ExecuteScalar());
  327. }
  328. catch (Exception ex)
  329. {
  330. Console.WriteLine(ex.Message);
  331. }
  332. finally
  333. {
  334. DBHelper.conn.Close();
  335. }
  336. // 已有记录存在,?: 相当于if else,三元运算符;
  337. returnValue = result > 0 ? true : false;
  338. return returnValue;
  339. }
  340. //***************************************子步骤2,结束了****************************************
  341. /// <summary>
  342. /// 添加好友,第5步
  343. /// </summary>
  344. private int AddFriend(int friendId)//朋友号码:10016,加过去,作为10000的朋友,直接加过去
  345. {
  346. int resunlt = 0; // 操作结果
  347. string sql = string.Format("INSERT INTO FRIENDS (HostId, FriendId) VALUES ({0},{1})",UserHelper.loginId, friendId);
  348. try
  349. {
  350. // 执行添加操作
  351. SqlCommand command = new SqlCommand(sql, DBHelper.conn);
  352. DBHelper.conn.Open();
  353. resunlt = command.ExecuteNonQuery();
  354. }
  355. catch (Exception ex)
  356. {
  357. Console.WriteLine(ex.Message);
  358. }
  359. finally
  360. {
  361. DBHelper.conn.Close();
  362. }
  363. return resunlt;
  364. }
  365. //*************************************子步骤5,结束了*************************
  366. /// <summary>
  367. /// 添加好友子步骤4:发出添加好友请求;接触到一个表:消息表;
  368. /// </summary>
  369. private int SendRequest(int friendId) //10009
  370. {
  371. int resunlt = 0; // 操作结果
  372. string sql = string.Format("INSERT INTO Messages(FromUserId, ToUserId, MessageTypeId, MessageState) VALUES ({0},{1},{2},{3})",
  373. UserHelper.loginId, friendId, 2, 0);//2:添加好友的消息;0:消息未读;
  374. //10000加10009
  375. try
  376. {
  377. // 执行添加操作
  378. SqlCommand command = new SqlCommand(sql, DBHelper.conn);
  379. DBHelper.conn.Open();
  380. resunlt = command.ExecuteNonQuery();
  381. }
  382. catch (Exception ex)
  383. {
  384. Console.WriteLine(ex.Message);
  385. }
  386. finally
  387. {
  388. DBHelper.conn.Close();
  389. }
  390. return resunlt;
  391. }
  392. private void pnlBaseCondition_Paint(object sender, PaintEventArgs e)
  393. {
  394. }
  395. //***************************************************子步骤4结束了**********************
  396. }
  397. }
视频课堂https://edu.csdn.net/course/play/7621

文章来源: aaaedu.blog.csdn.net,作者:tea_year,版权归原作者所有,如需转载,请联系作者。

原文链接:aaaedu.blog.csdn.net/article/details/50486828

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200