翼度科技»论坛 编程开发 .net 查看内容

循环可变化的集合 数组 datatable 等 || c# winfrom DataGridView 动态UI下

3

主题

3

帖子

9

积分

新手上路

Rank: 1

积分
9
Gif演示


 

 

 
分解步骤

1,使用组件DataGridView
2,使用DataSource来控制表格展示的数据来源(注意:来源需要是DataTable类型)
3,需要用到异步线程。如果是不控制数据源的话,需要使用UI安全线程;(使用Control.Invoke或Control.BeginInvoke方法)
4,DataGridView的列如果设置图片,尽量代码设置
5,DataTable类型也是可以使用LINQ的,参考:AsEnumerable
完整代码
  1. using Newtonsoft.Json;
  2. using Sunny.UI.Win32;
  3. using Sunny.UI;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Drawing;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. using WinApp.i18n;
  14. using WinApp.Until;
  15. using WinApp.ViewModel;
  16. using static System.Net.Mime.MediaTypeNames;
  17. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  18. using System.Security.Cryptography;
  19. namespace WinApp.View
  20. {
  21.     public partial class DownloadList : UserControl
  22.     {
  23.         /// <summary>
  24.         /// 开启任务的开关(作用:禁止重复启动任务)
  25.         /// </summary>
  26.         private static bool _taskSwitch = true;
  27.         /// <summary>
  28.         /// 任务中的小开关(作用:如果被外部干涉,则进行退出执行任务内容)
  29.         /// </summary>
  30.         private static bool _taskCondition = true;
  31.         public DataTable _table;
  32.         List<DownloadListDto> _mainList;
  33.         public UILabel _lbNotData;
  34.         public DownloadList()
  35.         {
  36.             InitializeComponent();
  37.             var mainTitle = string.Empty;
  38.             mainTitle = Language.GetLang("downloadTitle1");
  39.             mainTitle += "\r" + Language.GetLang("downloadTitle2");
  40.             this.uiPanel1.Text = mainTitle;
  41.             uiDataGridView1.ColumnHeadersVisible = false;
  42.             uiDataGridView1.RowTemplate.Height = 65;
  43.             uiDataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
  44.             _lbNotData = new UILabel();
  45.             _lbNotData.Text = "No more data available";
  46.             _lbNotData.Cursor = Cursors.Hand;
  47.             _lbNotData.TextAlign = ContentAlignment.MiddleCenter;
  48.             _lbNotData.Location = new Point(450, 50);
  49.             _lbNotData.Width = 200;
  50.             _lbNotData.Visible = false;
  51.             this.uiPanel2.Controls.Add(_lbNotData);
  52.         }
  53.         private void DownloadList_Load(object sender, EventArgs e)
  54.         {
  55.             QueryData();
  56.         }
  57.         public void SetCondition(bool setValue)
  58.         {
  59.             _taskCondition = setValue;
  60.         }
  61.         public async Task DownloadAllAsync()
  62.         {
  63.             if (_taskSwitch)
  64.             {
  65.                 if (_table.Rows.Count <= 0)
  66.                 {
  67.                     UIMessageDialog.ShowMessageDialog("No more data available", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
  68.                     return;
  69.                 }
  70.                 //已经执行,请勿重复执行;
  71.                 _taskSwitch = false;
  72.                 foreach (DataRow row in _table.Rows)
  73.                 {
  74.                     row["Status"] = "2";//设置为下载中的状态
  75.                     uiDataGridView1.Refresh();
  76.                 }
  77.                 while (_table.Rows.Count > 0 && _taskCondition)
  78.                 {//如果列表有数据就一直循环进行下载删除
  79.                     var firstRow = _table.Rows[0];
  80.                     if (firstRow == null)
  81.                     {//第一个元素等于NULL
  82.                         return;
  83.                     }
  84.                     for (int j = 0; j <= 100; j++)//模拟进度条
  85.                     {
  86.                         if (_taskCondition)
  87.                         {//如果没有暂停
  88.                             await Task.Delay(10); // wait for 100 milliseconds
  89.                             firstRow["DownloadProgress"] = j.ToString();
  90.                         }
  91.                         else
  92.                         {//暂停
  93.                             firstRow["Status"] = "1";
  94.                         }
  95.                     }
  96.                     if (_taskCondition)
  97.                     {
  98.                         // 获取当前行的数据行                    
  99.                         var _Id = (int)firstRow["Id"];
  100.                         // 使用Linq查询匹配的行
  101.                         var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
  102.                         _table.Rows.Remove(rowsToDelete);
  103.                     }
  104.                 }
  105.                 //foreach (DataRow row in _table.Rows)
  106.                 //{
  107.                 //    row["Status"] = "2";
  108.                 //    for (int j = 0; j <= 100; j++)
  109.                 //    {
  110.                 //        if (_taskCondition)
  111.                 //        {
  112.                 //            await Task.Delay(10); // wait for 100 milliseconds
  113.                 //            row["DownloadProgress"] = j.ToString();
  114.                 //        }
  115.                 //        else
  116.                 //        {
  117.                 //            row["Status"] = "1";
  118.                 //        }
  119.                 //    }
  120.                 //    // 获取当前行的数据行                    
  121.                 //    var _Id = (int)row["Id"];
  122.                 //    // 使用Linq查询匹配的行
  123.                 //    var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
  124.                 //    _table.Rows.Remove(rowsToDelete);
  125.                 //}
  126.                 //foreach (var item in _mainList)
  127.                 //{
  128.                 //    item.Status = 2;
  129.                 //    uiDataGridView1.Refresh();
  130.                 //    for (int i = 0; i < 100; i++)
  131.                 //    {
  132.                 //        if (_taskCondition)
  133.                 //        {
  134.                 //            await Task.Delay(100); // wait for 100 milliseconds
  135.                 //            item.DownloadProgress = i.ToString();
  136.                 //            uiDataGridView1.Refresh();
  137.                 //        }
  138.                 //        else
  139.                 //        {
  140.                 //            item.Status = 1;
  141.                 //            return;
  142.                 //        }
  143.                 //    }
  144.                 //}
  145.                 //执行完毕,则可以重新执行
  146.                 _taskSwitch = true;
  147.             }
  148.             else
  149.             {
  150.                 //因为此次没有执行,下次允许执行;
  151.                 _taskSwitch = true;
  152.                 return;
  153.             }
  154.         }
  155.         public void PauseAll()
  156.         {
  157.             SetCondition(false);
  158.             //获取所有已经开始的数据
  159.             var pauseList = _table.AsEnumerable().Where(row => row.Field<int>("Status") == 2);
  160.             foreach (DataRow item in pauseList)
  161.             {
  162.                 item["Status"] = "1";
  163.                 uiDataGridView1.Refresh();
  164.             }
  165.         }
  166.         public void DeleteAll()
  167.         {            
  168.             SetCondition(false);
  169.          
  170.             // 清除所有行
  171.             _table.Clear();
  172.             uiDataGridView1.Refresh();
  173.             this.uiDataGridView1.Refresh();
  174.         }
  175.         public void QueryData()
  176.         {
  177.             LoadingHelper.ShowLoadingScreen();
  178.             _mainList = new List<DownloadListDto>();
  179.             _mainList.Add(new DownloadListDto()
  180.             {
  181.                 Id = 1,
  182.                 Title = "A1" + Environment.NewLine + "B1",
  183.                 Status = 1,
  184.                 DownloadProgress = "0"
  185.             });
  186.             _mainList.Add(new DownloadListDto()
  187.             {
  188.                 Id = 2,
  189.                 Title = "A2" + Environment.NewLine + "B2",
  190.                 Status = 1,
  191.                 DownloadProgress = "0"
  192.             });
  193.             _mainList.Add(new DownloadListDto()
  194.             {
  195.                 Id = 3,
  196.                 Title = "A3" + Environment.NewLine + "B3",
  197.                 Status = 1,
  198.                 DownloadProgress = "0"
  199.             });
  200.             _mainList.Add(new DownloadListDto()
  201.             {
  202.                 Id = 4,
  203.                 Title = "A4" + Environment.NewLine + "B4",
  204.                 Status = 1,
  205.                 DownloadProgress = "0"
  206.             });
  207.             _mainList.Add(new DownloadListDto()
  208.             {
  209.                 Id = 5,
  210.                 Title = "A5" + Environment.NewLine + "B5",
  211.                 Status = 1,
  212.                 DownloadProgress = "0"
  213.             });
  214.             _table = _mainList.ToDataTable();
  215.             this.uiDataGridView1.DataSource = _table;
  216.             LoadingHelper.CloseForm();
  217.             uiDataGridView1.ClearSelection();
  218.         }
  219.         private void uiDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
  220.         {
  221.             DataGridViewRow row = uiDataGridView1.Rows[e.RowIndex];
  222.             if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clTitle")
  223.             {
  224.                 if (row.Cells["clStatus"].Value is int)
  225.                 {
  226.                     var intStatus = (int)row.Cells["clStatus"].Value;
  227.                     if (intStatus == 1)
  228.                     {
  229.                         row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/downLoad.png");
  230.                         row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
  231.                     }
  232.                     else if (intStatus == 2)
  233.                     {
  234.                         row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/pause.png");
  235.                         row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
  236.                         //row.Cells["clOpDelete"].Value = null;
  237.                     }
  238.                     else
  239.                     {
  240.                         // 创建一个1x1像素的透明图像
  241.                         Bitmap transparentImage = new Bitmap(1, 1);
  242.                         transparentImage.SetPixel(0, 0, Color.Transparent);
  243.                         row.Cells["clOpDown"].Value = transparentImage;
  244.                         row.Cells["clOpDelete"].Value = transparentImage;
  245.                     }
  246.                 }
  247.             }
  248.         }
  249.         private void uiDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  250.         {
  251.             //uiDataGridView1.ClearSelection();
  252.         }
  253.         private async void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
  254.         {
  255.             if (uiDataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex >= 0)
  256.             {
  257.                 // 获取当前行的数据行
  258.                 var currentRow = uiDataGridView1.Rows[e.RowIndex];
  259.                 var _Id = (int)currentRow.Cells["clId"].Value;
  260.                 if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDown")
  261.                 {
  262.                     //var currentData = _mainList.Find(x => x.Id == _Id);
  263.                     var currentData = _table.AsEnumerable().FirstOrDefault(x => x.Field<int>("Id") == _Id);
  264.                     if (currentData != null)
  265.                     {
  266.                         if (currentData["Status"].ToString() == "1")
  267.                         {//1代表 未下载
  268.                             currentData["Status"] = "2";//修改图标
  269.                             uiDataGridView1.Refresh();
  270.                         }
  271.                         else
  272.                         {//2代表 正在下载
  273.                             _taskCondition = false;//终止执行任务
  274.                             currentData["Status"] = "1";//修改图标
  275.                             uiDataGridView1.Refresh();
  276.                         }
  277.                         //currentData.Status = 1;
  278.                         //_taskCondition = false;
  279.                         //uiDataGridView1.Refresh();
  280.                     }
  281.                 }
  282.                 if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDelete")
  283.                 {
  284.                     // 使用Linq查询匹配的行
  285.                     var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
  286.                     _table.Rows.Remove(rowsToDelete);
  287.                 }
  288.             }
  289.         }
  290.         public void DeleteMainData(int Id)
  291.         {
  292.             var currentData = _mainList.Find(x => x.Id == Id);
  293.             if (currentData != null)
  294.             {
  295.                 _mainList.Remove(currentData);
  296.                 uiDataGridView1.DataSource = _mainList;
  297.                 uiDataGridView1.Refresh();
  298.             }
  299.         }
  300.         private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
  301.         {
  302.             uiDataGridView1.Visible = true;
  303.             _lbNotData.Visible = false;
  304.             DataGridView dataGridView = (DataGridView)sender;
  305.             if (dataGridView.Rows.Count == 0)
  306.             {
  307.                 uiDataGridView1.Dock = DockStyle.None;
  308.                 uiDataGridView1.Visible = false;
  309.                 _lbNotData.Visible = true;
  310.             }
  311.         }
  312.         private void uiDataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
  313.         {
  314.             // 取消默认的错误处理行为
  315.             e.ThrowException = false;
  316.             // 获取出错的单元格
  317.             DataGridViewCell errorCell = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
  318.             // 获取出错的数据
  319.             object errorValue = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
  320.             // 自定义错误处理逻辑
  321.             MessageBox.Show("数据错误:" + e.Exception.Message);
  322.             // 可以将出错的单元格的值重置为默认值
  323.             errorCell.Value = errorCell.DefaultNewRowValue;
  324.         }
  325.     }
  326. }
复制代码
 
结语

上面完整代码是.cs的代码。大家拷贝本地使用的时候需要在UI界面进行拖拉组件。本例子用的是winform SunnyUI 的框架 。框架文档在这里:文档预览 - Gitee.com

来源:https://www.cnblogs.com/BFMC/p/18020935
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具