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

这篇具有很好参考价值的文章主要介绍了循环可变化的集合 数组 datatable 等 || c# winfrom DataGridView 动态UI下载功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Gif演示

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

 

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

 

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

 

分解步骤

1,使用组件DataGridView

2,使用DataSource来控制表格展示的数据来源(注意:来源需要是DataTable类型)

3,需要用到异步线程。如果是不控制数据源的话,需要使用UI安全线程;(使用Control.Invoke或Control.BeginInvoke方法)

4,DataGridView的列如果设置图片,尽量代码设置

5,DataTable类型也是可以使用LINQ的,参考:AsEnumerable

完整代码

using Newtonsoft.Json;
using Sunny.UI.Win32;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.i18n;
using WinApp.Until;
using WinApp.ViewModel;
using static System.Net.Mime.MediaTypeNames;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Security.Cryptography;

namespace WinApp.View
{
    public partial class DownloadList : UserControl
    {
        /// <summary>
        /// 开启任务的开关(作用:禁止重复启动任务)
        /// </summary>
        private static bool _taskSwitch = true;
        /// <summary>
        /// 任务中的小开关(作用:如果被外部干涉,则进行退出执行任务内容)
        /// </summary>
        private static bool _taskCondition = true;

        public DataTable _table;
        List<DownloadListDto> _mainList;

        public UILabel _lbNotData;

        public DownloadList()
        {
            InitializeComponent();
            var mainTitle = string.Empty;
            mainTitle = Language.GetLang("downloadTitle1");
            mainTitle += "\r" + Language.GetLang("downloadTitle2");
            this.uiPanel1.Text = mainTitle;

            uiDataGridView1.ColumnHeadersVisible = false;
            uiDataGridView1.RowTemplate.Height = 65;
            uiDataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;

            _lbNotData = new UILabel();
            _lbNotData.Text = "No more data available";
            _lbNotData.Cursor = Cursors.Hand;
            _lbNotData.TextAlign = ContentAlignment.MiddleCenter;
            _lbNotData.Location = new Point(450, 50);
            _lbNotData.Width = 200;
            _lbNotData.Visible = false;
            this.uiPanel2.Controls.Add(_lbNotData);
        }

        private void DownloadList_Load(object sender, EventArgs e)
        {
            QueryData();
        }

        public void SetCondition(bool setValue)
        {
            _taskCondition = setValue;
        }
        public async Task DownloadAllAsync()
        {
            if (_taskSwitch)
            {
                if (_table.Rows.Count <= 0)
                {
                    UIMessageDialog.ShowMessageDialog("No more data available", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                    return;
                }


                //已经执行,请勿重复执行;
                _taskSwitch = false;


                foreach (DataRow row in _table.Rows)
                {
                    row["Status"] = "2";//设置为下载中的状态
                    uiDataGridView1.Refresh();
                }

                while (_table.Rows.Count > 0 && _taskCondition)
                {//如果列表有数据就一直循环进行下载删除
                    var firstRow = _table.Rows[0];
                    if (firstRow == null)
                    {//第一个元素等于NULL
                        return;
                    }

                    for (int j = 0; j <= 100; j++)//模拟进度条
                    {
                        if (_taskCondition)
                        {//如果没有暂停
                            await Task.Delay(10); // wait for 100 milliseconds
                            firstRow["DownloadProgress"] = j.ToString();

                        }
                        else
                        {//暂停
                            firstRow["Status"] = "1";
                        }
                    }

                    if (_taskCondition)
                    {
                        // 获取当前行的数据行                    
                        var _Id = (int)firstRow["Id"];
                        // 使用Linq查询匹配的行
                        var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                        _table.Rows.Remove(rowsToDelete);
                    }
                }

                //foreach (DataRow row in _table.Rows)
                //{
                //    row["Status"] = "2";

                //    for (int j = 0; j <= 100; j++)
                //    {
                //        if (_taskCondition)
                //        {
                //            await Task.Delay(10); // wait for 100 milliseconds
                //            row["DownloadProgress"] = j.ToString();
                //        }
                //        else
                //        {
                //            row["Status"] = "1";
                //        }
                //    }
                //    // 获取当前行的数据行                    
                //    var _Id = (int)row["Id"];
                //    // 使用Linq查询匹配的行
                //    var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                //    _table.Rows.Remove(rowsToDelete);
                //}


                //foreach (var item in _mainList)
                //{
                //    item.Status = 2;
                //    uiDataGridView1.Refresh();

                //    for (int i = 0; i < 100; i++)
                //    {
                //        if (_taskCondition)
                //        {
                //            await Task.Delay(100); // wait for 100 milliseconds
                //            item.DownloadProgress = i.ToString();
                //            uiDataGridView1.Refresh();
                //        }
                //        else
                //        {
                //            item.Status = 1;
                //            return;
                //        }
                //    }
                //}

                //执行完毕,则可以重新执行
                _taskSwitch = true;
            }
            else
            {
                //因为此次没有执行,下次允许执行;
                _taskSwitch = true;
                return;
            }
        }

        public void PauseAll()
        {
            SetCondition(false);

            //获取所有已经开始的数据

            var pauseList = _table.AsEnumerable().Where(row => row.Field<int>("Status") == 2);
            foreach (DataRow item in pauseList)
            {
                item["Status"] = "1";
                uiDataGridView1.Refresh();
            }

        }

        public void DeleteAll()
        {            
            SetCondition(false);
         
            // 清除所有行
            _table.Clear();
            uiDataGridView1.Refresh();
            this.uiDataGridView1.Refresh();
        }

        public void QueryData()
        {

            LoadingHelper.ShowLoadingScreen();

            _mainList = new List<DownloadListDto>();
            _mainList.Add(new DownloadListDto()
            {
                Id = 1,
                Title = "A1" + Environment.NewLine + "B1",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 2,
                Title = "A2" + Environment.NewLine + "B2",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 3,
                Title = "A3" + Environment.NewLine + "B3",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 4,
                Title = "A4" + Environment.NewLine + "B4",
                Status = 1,
                DownloadProgress = "0"
            });
            _mainList.Add(new DownloadListDto()
            {
                Id = 5,
                Title = "A5" + Environment.NewLine + "B5",
                Status = 1,
                DownloadProgress = "0"
            });


            _table = _mainList.ToDataTable();
            this.uiDataGridView1.DataSource = _table;

            LoadingHelper.CloseForm();
            uiDataGridView1.ClearSelection();
        }

        private void uiDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridViewRow row = uiDataGridView1.Rows[e.RowIndex];

            if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clTitle")
            {
                if (row.Cells["clStatus"].Value is int)
                {
                    var intStatus = (int)row.Cells["clStatus"].Value;
                    if (intStatus == 1)
                    {
                        row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/downLoad.png");
                        row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
                    }
                    else if (intStatus == 2)
                    {
                        row.Cells["clOpDown"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/pause.png");
                        row.Cells["clOpDelete"].Value = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/delete1.png");
                        //row.Cells["clOpDelete"].Value = null;
                    }
                    else
                    {
                        // 创建一个1x1像素的透明图像
                        Bitmap transparentImage = new Bitmap(1, 1);
                        transparentImage.SetPixel(0, 0, Color.Transparent);
                        row.Cells["clOpDown"].Value = transparentImage;
                        row.Cells["clOpDelete"].Value = transparentImage;
                    }
                }

            }
        }

        private void uiDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //uiDataGridView1.ClearSelection();
        }

        private async void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (uiDataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex >= 0)
            {
                // 获取当前行的数据行
                var currentRow = uiDataGridView1.Rows[e.RowIndex];
                var _Id = (int)currentRow.Cells["clId"].Value;
                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDown")
                {

                    //var currentData = _mainList.Find(x => x.Id == _Id);
                    var currentData = _table.AsEnumerable().FirstOrDefault(x => x.Field<int>("Id") == _Id);
                    if (currentData != null)
                    {
                        if (currentData["Status"].ToString() == "1")
                        {//1代表 未下载

                            currentData["Status"] = "2";//修改图标
                            uiDataGridView1.Refresh();

                        }
                        else
                        {//2代表 正在下载

                            _taskCondition = false;//终止执行任务
                            currentData["Status"] = "1";//修改图标
                            uiDataGridView1.Refresh();

                        }
                        //currentData.Status = 1;
                        //_taskCondition = false;
                        //uiDataGridView1.Refresh();
                    }
                }

                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "clOpDelete")
                {

                    // 使用Linq查询匹配的行
                    var rowsToDelete = _table.AsEnumerable().FirstOrDefault(row => row.Field<int>("Id") == _Id);
                    _table.Rows.Remove(rowsToDelete);
                }
            }
        }
        public void DeleteMainData(int Id)
        {
            var currentData = _mainList.Find(x => x.Id == Id);
            if (currentData != null)
            {
                _mainList.Remove(currentData);
                uiDataGridView1.DataSource = _mainList;
                uiDataGridView1.Refresh();
            }
        }

        private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            uiDataGridView1.Visible = true;
            _lbNotData.Visible = false;
            DataGridView dataGridView = (DataGridView)sender;
            if (dataGridView.Rows.Count == 0)
            {
                uiDataGridView1.Dock = DockStyle.None;
                uiDataGridView1.Visible = false;

                _lbNotData.Visible = true;
            }
        }

        private void uiDataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 取消默认的错误处理行为
            e.ThrowException = false;

            // 获取出错的单元格
            DataGridViewCell errorCell = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

            // 获取出错的数据
            object errorValue = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            // 自定义错误处理逻辑
            MessageBox.Show("数据错误:" + e.Exception.Message);

            // 可以将出错的单元格的值重置为默认值
            errorCell.Value = errorCell.DefaultNewRowValue;
        }
    }
}

 

结语

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

到了这里,关于循环可变化的集合 数组 datatable 等 || c# winfrom DataGridView 动态UI下载功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# 读取二维数组集合输出到Word预设表格

    目录 应用场景 设计约定 范例运行环境 配置Office DCOM 实现代码 组件库引入 核心代码 DataSet转二维数组 导出写入WORD表格 调用举例 小结 存储或导出个人WORD版简历是招聘应用系统中的常用功能,我们通常会通过应用系统采集用户的个人简历信息到数据库,许多情况下我们会读

    2024年03月23日
    浏览(34)
  • C#入门及进阶|数组和集合(十):Queue类

            在某种线性表中,需要加入的元素总是插入到线性表的末端,且总是从线性表的头部取出或删除元素,我们把这种线性表称为队列。         在C#中,通过Queue集合来封装对队列的操作,在队列中对元素的操作遵循“先进先出”的原则。Queue类常用的属性和方法

    2024年02月19日
    浏览(29)
  • 【Unity 3D】C#中数组、集合、栈、队列、哈希表、字典的讲解(附测试代码)

    觉得有帮助请点赞关注收藏~~~ 数组时有序的元素序列,存在有限个相同的变量的集合叫做数组名,组成数组二点各个变量称为数组的分量,又称为数组的元素,有时也称为下标变量,用于区分数组的各个元素的数组编号称为下标。 初始化数组 datatype [] arrayname datetype指定存储

    2024年02月04日
    浏览(28)
  • C# 给winfrom窗体添加皮肤控件

    如何快速给C# winform添加好看的皮肤C# Winform中窗体的美化 SkinEngine的应用 皮肤控件换肤素材包,IrisSkin2.dll皮肤素材资源下载  压缩包内一共有22种皮肤素材,使用说明:把控件拖到你的form上,只需一行代码,即可实现整个form包括其所有控件的皮肤的更换,  总共有几十套皮肤

    2024年02月05日
    浏览(35)
  • C#之Winfrom自定义输入框对话框。

    在你的程序中,在需要触发输入框的地方添加一个按钮或其他事件处理器。例如,你可以在按钮点击事件中执行相应的代码和逻辑。 通过以上步骤,你可以在 WinForms 程序中创建一个带有输入框的自定义窗体,并在点击确定按钮后获取用户输入的值。确保根据实际需求修改输

    2024年02月14日
    浏览(26)
  • WinFrom、C# 学习记录五 开发一个鼠标自动点击小软件

            经常会被问到需要点击软件的,主要都是玩游戏的盆友,但是也有其它用途的。所以简单弄了一个,打算每当有时间,有需求,就加一些小功能。         这里主要是要记录一下相关开发工作,也记录一些使用/更新的信息。         【2022/08/22】版本v1.0(初始版

    2024年02月16日
    浏览(34)
  • C# Winfrom实例:武汉智能安检闸机数据接收和解析

    项目介绍: 本实例主要是接收安检闸机的数据解析并显示到界面上,只做功能实现,不做界面美化 硬件:闸机一个、网线一根、电脑主机 开发环境:vs2017 系统:win10 涵盖知识点:tcp通讯、文件写入、多线程,委托、类型转换等 软件操作流程: 点击开始监听按钮,8999要是未

    2024年02月19日
    浏览(26)
  • C#中DataTable实现筛选查询

    2024年02月15日
    浏览(26)
  • C#使用DataGridView模拟绘图

    接到一个需求,绘制一个水管线的图片,这种管线可以有12种分段方法,最后将这12种分段方法合并后在一条水管线上展示,要求: ⒈支持分段的属性展示; ⒉要求每个分段都能清晰展示,分段数在0(没有分段)~100之间,水管线长度不定; 3、每个分段的属性都有值,可以更

    2024年02月16日
    浏览(30)
  • C# winfrom实例:四路激光测距雷达数据采集和波形图绘制

       1.所述产品 产品型号: TFmini Plus 相关资料下载地址:http://www.benewake.com/download 产品名称:TFmini Plus激光雷达模组 制造商 公司:北醒(北京)光子科技有限公司  2.产品功能:TFmini Plus是基于TFmini的升级项目,它是一款小型化,单点测距的产品,基于TOF(飞行 时间)原理,

    2024年02月19日
    浏览(27)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包