c# winfrom DataGridView 動態UI下載功能(內含GIF圖) || 迴圈可變化的集合 數組 datatable 等

来源:https://www.cnblogs.com/BFMC/p/18020935
-Advertisement-
Play Games

Gif演示 分解步驟 1,使用組件DataGridView 2,使用DataSource來控製表格展示的數據來源(註意:來源需要是DataTable類型) 3,需要用到非同步線程。如果是不控制數據源的話,需要使用UI安全線程;(使用Control.Invoke或Control.BeginInvoke方 ...


Gif演示

 

分解步驟

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

從前慢,車馬慢。 一生只愛一個人。
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、程式計數器 程式計數器記憶體很小,可以看作是當前線程所執行位元組碼的行號指示器。 有了它,程式就能被正確的執行。 因為有線程切換的存在,則每個線程必須有各自獨立的程式計數器,即線程私有的記憶體。 這裡再解釋一下什麼是線程切換,線程切換指的是: 單處理器在執行多線程時所進行的線程切換,多線程的交替運行會 ...
  • 常見內置序列類型(Sequence Type) 類型 英文名 對應關鍵字 構造函數 是否可變 列表 list list list() 可變 元組 tuple tuple tuple() 不可變 數字序列:range range range range() 不可變 文本序列:字元串 string st ...
  • 最近看幾個老項目的SQL條件中使用了1=1,想想自己也曾經這樣寫過,略有感觸,特別拿出來說道說道。編寫SQL語句就像炒菜,每一種調料的使用都會影響菜品的最終味道,每一個SQL條件的加入也會影響查詢的執行效率。那麼 1=1 存在什麼樣的問題呢?為什麼又會使用呢? ...
  • Unity 預設可以序列化值類型, Serializable屬性修飾的類型, 派生自UnityEngine.Object的類型, 通常這些類型已經足以供日常使用了. 但是有時我們希望在編輯器面板上序列化一個介面或者抽象類, 則需要用到 SerializeReference屬性. 假定我們有一個介面I ...
  • 背景 在瀏覽器中訪問本地靜態資源html網頁時,可能會遇到跨域問題如圖。 是因為瀏覽器預設啟用了同源策略,即只允許載入與當前網頁具有相同源(協議、功能變數名稱和埠)的內容。 WebView2預設情況下啟用了瀏覽器的同源策略,即只允許載入與主機相同源的內容。所以如果我們把靜態資源發佈到iis或者通過node ...
  • 一:nacos https://nacos.io/docs/latest/what-is-nacos/ https://github.com/alibaba/nacos 二:consul https://developer.hashicorp.com/consul/docs?product_inte ...
  • 概述:MVVM Toolkit是.NET平臺的強大工具包,旨在簡化MVVM應用程式開發。提供基礎功能如ViewModelBase和RelayCommand,支持數據綁定和命令綁定,通過Messenger實現消息訂閱發佈。其高級功能包括ObservableObject和WeakEventListene ...
  • 概述:.NET中的IConfiguration介面提供了一種多源讀取配置信息的靈活機制,包括JSON、XML、INI文件和環境變數。通過示例,清晰演示了從這些不同源中讀取配置的方法,使配置獲取變得方便且易於擴展。這種方式適用於不同場景,如API密鑰、資料庫連接等,為應用提供了高度可配置性。 在.NE ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...