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
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...