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 MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...