NEWS

[DEVEXPRESS] Sử dụng RealTimeSource để đọc dữ liệu theo thời gian thực vào Gridview C#

[DEVEXPRESS] Sử dụng RealTimeSource để đọc dữ liệu theo thời gian thực vào Gridview C#
Đăng bởi: Thảo Meo - Lượt xem: 4110 13:55:42, 18/11/2022C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình tiếp tục hướng dẫn các bạn cách sử dụng RealTimeSource vào gridview Devexpress để tải dữ liệu theo thời gian thực.

[DEVEXPRESS] Load data RealTime to GridView using RealTimeSource C#

Dưới đây, là hình ảnh demo ứng dụng:

live_data

Ở bài viết demo này, mình sử dụng NodeJs để tạo 1 server sử dụng Socket.IO để truyền dữ liệu liên tục về cho Winform.

Chi tiết các bạn, có thể tham khảo ở Video demo:

Source code Node JS:

const ex = require('express');
const router = ex.Router();
var exServer = require('http').createServer(ex)
exServer.listen(1500)
console.log("Server running at 127.0.0.1:1500");
var server = require("socket.io").Server
var socketIO = new server(exServer)

var generateNumber = function (min, max) {
    if (min > max) {
        throw new Error('Minimum value should be smaller than maximum value.');
    }
    var range = max - min;
    var result = (min + range * Math.random());
    return Number.parseFloat(result).toFixed(2);
};

socketIO.on("connect", (socketConnection) => {


    socketConnection.on('send', function (timeout) {
        console.log(timeout);
        setInterval(function () {

            var randomData = function (name) {
                const timestamp = Date.now() ;
                return { Currency: name, Rate: generateNumber(1.0, 2.0), Bid: generateNumber(1.0, 2.0), Ask: generateNumber(1.0, 2.0), High: generateNumber(1.0, 2.0), Low: generateNumber(1.0, 2.0), Open: generateNumber(1.0, 2.0), Close: generateNumber(1.0, 2.0), TimeStamp: timestamp};
            }
            var sampleData = [];
            sampleData.push(randomData("VND/USD"));
            sampleData.push(randomData("VND/GBP"));
            sampleData.push(randomData("USD/EUR"));
            sampleData.push(randomData("JPY/USD"));
            sampleData.push(randomData("GDP/JPY"));
            sampleData.push(randomData("CAD/USD"));
            sampleData.push(randomData("USD/CHF"));
            sampleData.push(randomData("JPY/CHF"));
            sampleData.push(randomData("USD/CAD"));
            socketConnection.send(JSON.stringify(sampleData));
            console.log(sampleData);
        }, timeout);
    })

})

Ở server này, sẻ trả cho chúng ta dữ liệu tỷ giá theo thời gian thực, số liệu thì mình random nhé.

Và ở dưới Winform chúng ta sẻ Connect và đọc dữ liệu liên tục lên Gridview C#.

Trên C#, các bạn cần cài đặt thư viện Socket.IO từ nuget.

PM> NuGetInstall-Package SocketIOClient -Version 3.0.7-alpha.1

Full source code C#:

using DevExpress.ClipboardSource.SpreadsheetML;
using DevExpress.Data;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using SocketIOClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace RealTimeData
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
        }
        BindingList<DataExchange> listDataExchange;
        private  void Form1_Load(object sender, EventArgs e)
        {
            gridView1.OptionsMenu.ShowConditionalFormattingItem = true;
            lblSpeed.Text = "Speed: " + trackBarControl1.Value + " ms";
           listDataExchange = new BindingList<DataExchange>();
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());
            listDataExchange.Add(new DataExchange());

            RealTimeSource rts = new RealTimeSource()
            {
                DataSource = listDataExchange
            };
            gridControl1.DataSource = rts;
            this.FormClosing += Form1_FormClosing;

          
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client != null) {
                if (client.Connected)
                {
                    client.DisconnectAsync();
                }
            }
            
        }

        SocketIO client;
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
           
        }

        private async void trackBarControl1_EditValueChanged(object sender, EventArgs e)
        {
            if(client!= null) {
                await client.DisconnectAsync();
                await client.ConnectAsync();
            }
            lblSpeed.Text = "Speed: " + trackBarControl1.Value + " ms";
           

        }
    }

    public class DataExchange: INotifyPropertyChanged
    {
        private string _Currency;
        private double _Rate;
        public double _Bid;
        public double _Ask;
        public double _High;
        public double _Low;
        public double _Open;
        public double _Close;
        public long _TimeStamp;
       

        public string Currency
        {
            get
            {
                return _Currency;
            }
            set
            {
                _Currency = value;
                NotifyPropertyChanged("Currency");
            }
        }
        public double Rate
        {
            get
            {
                return _Rate;
            }
            set
            {
                _Rate = value;
                NotifyPropertyChanged("Rate");
            }
        }
        public double Bid
        {
            get
            {
                return _Bid;
            }
            set
            {
                _Bid = value;
                NotifyPropertyChanged("Bid");
            }
        }

        public double Ask
        {
            get
            {
                return _Ask;
            }
            set
            {
                _Ask = value;
                NotifyPropertyChanged("Ask");
            }
        }

        public double High
        {
            get
            {
                return _High;
            }
            set
            {
                _High = value;
                NotifyPropertyChanged("High");
            }
        }

        public double Low
        {
            get
            {
                return _Low;
            }
            set
            {
                _Low = value;
                NotifyPropertyChanged("Low");
            }
        }

        public double Open
        {
            get
            {
                return _Open;
            }
            set
            {
                _Open = value;
                NotifyPropertyChanged("Open");
            }
        }

        public double Close
        {
            get
            {
                return _Close;
            }
            set
            {
                _Close = value;
                NotifyPropertyChanged("Close");
            }
        }

        public long TimeStamp
        {
            get
            {
                return _TimeStamp;
            }
            set
            {
                _TimeStamp = value;
                NotifyPropertyChanged("TimeStamp");
            }
        }     
      
     

        public event PropertyChangedEventHandler PropertyChanged;
        void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[DEVEXPRESS] Sử dụng RealTimeSource để đọc dữ liệu theo thời gian thực vào Gridview C#
Đăng bởi: Thảo Meo - Lượt xem: 4110 13:55:42, 18/11/2022C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.