asp.net 创建定时器以更新Gridview

6yjfywim  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(118)

首先,我是新来的,所以请耐心等待。我创建了一个网页,其中有一个表单,人们可以填写并在链接到sqltable的gridview中显示条目。该页面的工作正常的一个用户,但如果多个用户正在使用的网站,我希望所有用户看到任何变化的sqltable自动。在阅读了多个网站后,听起来我想在GridView上使用计时器,但找不到任何关于如何做到这一点的东西。
如果有人能告诉我正确的方向?
ASPX

%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Workstation_Role.aspx.cs" Inherits="OnCallWeb.Dispatch_Policies.Workstation_Role" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;
        }
        .auto-style2 {
            font-size: 14pt;
        }
        .auto-style3 {
            font-size: 14pt;
            width: 56px;
            text-align: right;
        }
        .auto-style5 {
            font-size: 14pt;
            width: 311px;
        }
        .auto-style6 {
            font-size: 12pt;
        }
        .auto-style7 {
            font-size: 14pt;
            text-align: right;
        }
        .auto-style8 {
            text-align: center;
        }
        .auto-style9 {
            font-size: 14pt;
            margin-top: 9px;
        }
        .auto-style10 {
            font-size: 14pt;
            width: 214px;
            text-align: left;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <table class="auto-style1">
            <tr>
                <td class="auto-style3">Name:</td>
                <td class="auto-style5">
                    <asp:DropDownList ID="DropDownList1" runat="server" CssClass="auto-style2" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="Name" Width="300px">
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:OnCallWebConnectionString %>" SelectCommand="SELECT [Name] FROM [Personnel] ORDER BY [Name]"></asp:SqlDataSource>
                </td>
                <td class="auto-style10">Postion #: <asp:DropDownList ID="DropDownList3" runat="server" CssClass="auto-style2" Width="130px">
                        <asp:ListItem></asp:ListItem>
                        <asp:ListItem>1</asp:ListItem>
                        <asp:ListItem>Training 7</asp:ListItem>
                        <asp:ListItem>Training 8</asp:ListItem>
                        <asp:ListItem>Training 9</asp:ListItem>
                        <asp:ListItem>Office</asp:ListItem>
                    </asp:DropDownList>
                </td>
                <td class="auto-style2">
                    Roles:
             Roles:
                    <asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style2" Width="772px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="auto-style3">Status:</td>
                <td class="auto-style2" colspan="3">
                    <asp:DropDownList ID="DropDownList4" runat="server" CssClass="auto-style2" Width="223px">
                        <asp:ListItem>At Desk</asp:ListItem>
                        <asp:ListItem>Away From Desk</asp:ListItem>
                    </asp:DropDownList>
                &nbsp;Dispatcher Covering:
                    <asp:DropDownList ID="DropDownList2" runat="server" CssClass="auto-style2" DataSourceID="SqlDataSource3" DataTextField="Name" DataValueField="Name" Width="300px">
                    </asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:OnCallWebConnectionString %>" SelectCommand="SELECT [Name] FROM [PersonnelCovering] ORDER BY [Name]"></asp:SqlDataSource>
                    <asp:Button ID="btnSave" runat="server" CssClass="auto-style6" OnClick="btnSave_Click" Text="Add To List" BackColor="#006600" ForeColor="White" />
&nbsp;
                    <asp:Button ID="btnUpdate" runat="server" CssClass="auto-style6" OnClick="btnUpdate_Click" Text="Update" BackColor="Yellow" />
&nbsp;
                    <asp:Button ID="btnDelete" runat="server" CssClass="auto-style6" OnClick="btnDelete_Click" Text="Delete" BackColor="Red" ForeColor="White" />
&nbsp;
                    <asp:Button ID="btnCancel" runat="server" CssClass="auto-style6" OnClick="btnCancel_Click" Text="Clear" BorderColor="Black" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;
                    &nbsp;<asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="auto-style7" colspan="4">
                    <div class="auto-style8">
                    </div>
                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:OnCallWebConnectionString %>" SelectCommand="SELECT [Name], [Position], [Roles], [Status], [DispatcherCovering], [ID] FROM [Dispatcher_Roles]"></asp:SqlDataSource>
                </td>
            </tr>
        </table>
        <div>
                    <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" CssClass="auto-style9" Width="1757px" EmptyDataText="No Records Found!">
                        <Columns>
                            <asp:CommandField ShowSelectButton="True" />
                            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                            <asp:BoundField DataField="Position" HeaderText="Position" SortExpression="Position" />
                            <asp:BoundField DataField="Roles" HeaderText="Roles" SortExpression="Roles" />
                            <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
                            <asp:BoundField DataField="DispatcherCovering" HeaderText="DispatcherCovering" SortExpression="DispatcherCovering" />
                            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible="False" />
                        </Columns>
                    </asp:GridView>
        </div>
    </form>
</body>
</html>

代码隐藏

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Timers;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace OnCallWeb.Dispatch_Policies
{
    public partial class Workstation_Role : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["OnCallWebConnectionString"].ConnectionString;
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter adapter;
        DataTable dt;

        public void DataLoad()
        {
            if (Page.IsPostBack)
            {
                GridView1.DataBind();
            }
        }

        public void ClearAllData()
        {
            DropDownList1.SelectedValue = DropDownList1.Items[0].ToString();
            DropDownList2.SelectedValue = DropDownList2.Items[0].ToString();
            DropDownList3.SelectedValue = DropDownList3.Items[0].ToString();
            DropDownList4.SelectedValue = DropDownList4.Items[0].ToString();
            TextBox1.Text = "";
            lblMessage.Text = "";
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList1.SelectedValue = GridView1.SelectedRow.Cells[1].Text;
            DropDownList3.Text = GridView1.SelectedRow.Cells[2].Text;
            TextBox1.Text = GridView1.SelectedRow.Cells[3].Text;
            DropDownList4.Text = GridView1.SelectedRow.Cells[4].Text;
            DropDownList2.Text = GridView1.SelectedRow.Cells[5].Text;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (TextBox1.Text != "" && DropDownList1.SelectedValue != "" && DropDownList3.SelectedValue != "")
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();
                    cmd = new SqlCommand("Insert into Dispatcher_Roles (Name, Position, Roles, Status, DispatcherCovering) Values(@Name, @Position, @Roles, @Status, @DispatcherCovering)", con);
                    cmd.Parameters.AddWithValue("@Name", DropDownList1.SelectedValue);
                    cmd.Parameters.AddWithValue("@Position", DropDownList3.SelectedValue);
                    cmd.Parameters.AddWithValue("@Roles", TextBox1.Text);
                    cmd.Parameters.AddWithValue("@Status", DropDownList4.SelectedValue);
                    cmd.Parameters.AddWithValue("@DispatcherCovering", DropDownList2.SelectedValue);
                    cmd.ExecuteNonQuery();
                    con.Close();
                    DataLoad();
                    ClearAllData();
                }
            }
            else
            {
                lblMessage.Text = "***Fill In All Information***";
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (TextBox1.Text != "" || DropDownList1.Text !="" || DropDownList2.Text !="")
                
            {
                using (con = new SqlConnection(cs))
                {
                    con.Open();
                    cmd = new SqlCommand("Update Dispatcher_Roles Set Name=@Name, Position=@Position, Roles=@Roles, Status=@Status, DispatcherCovering=@DispatcherCovering where Name=@Name", con);
                    cmd.Parameters.AddWithValue("@Name", DropDownList1.SelectedValue);
                    cmd.Parameters.AddWithValue("@Position", DropDownList3.SelectedValue);
                    cmd.Parameters.AddWithValue("@Roles", TextBox1.Text);
                    cmd.Parameters.AddWithValue("@Status", DropDownList4.SelectedValue);
                    cmd.Parameters.AddWithValue("@DispatcherCovering", DropDownList2.SelectedValue);

                    cmd.ExecuteNonQuery();
                    con.Close();
                    DataLoad();
                    ClearAllData();
                }
            }
            else
            {
                lblMessage.Text = "Fill In All All Fields";
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            using(con=new SqlConnection(cs))
            {
                con.Open();
                cmd = new SqlCommand("Delete From Dispatcher_Roles where Name=@Name", con);
                cmd.Parameters.AddWithValue("@Name", GridView1.SelectedRow.Cells[1].Text);
                cmd.ExecuteNonQuery();                
                con.Close();
                DataLoad();
                ClearAllData();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearAllData();
        }
    }
}
kgsdhlau

kgsdhlau1#

要实现多个用户查看网格视图的实时更新,可以考虑使用ASP.NET中的SignalR库。SignalR允许您通过启用服务器端代码将内容即时推送到连接的客户端来构建实时Web应用程序。
下面是如何使用SignalR实现网格视图的实时更新:
步骤1:安装SignalR

  • 在Visual Studio中,右键单击项目并选择“管理NuGet包”。
  • 搜索“Microsoft.AspNet.SignalR”并安装该软件包。

步骤2:创建SignalR Hub

  • 向项目中添加一个新类,并将其命名为“GridUpdateHub.cs”。
  • 从SignalR提供的Hub继承该类。
  • 在集线器中实现一个方法,该方法将被调用以向客户端发送更新。例如,您可以创建一个名为“UpdateGrid”的方法,将更新后的网格数据发送到连接的客户端。

使用Microsoft.AspNet.SignalR;
public class GridUpdateHub:Hub { public void UpdateGrid(string data){ //将更新的数据发送到所有连接的客户端客户端。All.updateGrid(data);{\fnSimHei\bord1\shad1\pos(200,288)}
步骤3:注册SignalR Hub

  • 打开项目中的“Global.asax.cs”文件。
  • Application_Start方法中添加以下代码以注册SignalR集线器:
using Microsoft.AspNet.SignalR;
  using System.Web.Routing;

  protected void Application_Start(object sender, EventArgs e)
  {
      // Register the SignalR hub
      RouteTable.Routes.MapHubs();
  }

步骤4:更新ASPX页面

  • 在ASPX页面中添加对SignalR JavaScript库的引用。
  • 添加JavaScript代码以连接到SignalR集线器并处理接收到的更新。将此代码放在<head>部分或<body>部分的末尾。

$(function(){ //连接到SignalR hub var hub = $.connection.gridUpdateHub;//定义一个客户端方法来处理接收到的更新hub.client.updateGrid = function(data){ //更新网格视图或使用更新后的数据执行任何其他必要的操作//例如,可以使用JavaScript/jQuery动态更新网格视图};//启动SignalR连接$.connection.hub.start();});
步骤5:从服务器端代码触发更新

  • 在您的服务器端代码中(例如,在btnSave_Click或btnUpdate_Click方法中),在保存或更新SQL表中的数据后,您可以使用SignalR集线器将更新的数据发送到连接的客户端。

使用Microsoft.AspNet.SignalR;
protected void btnSave_Click(object sender,EventArgs e){ //将数据保存到SQL表

// Get the updated data from the SQL table
  string updatedData = GetUpdatedGridData(); // Implement this method to retrieve the updated data

  // Send the updated data to connected clients
  var hubContext = GlobalHost.ConnectionManager.GetHubContext<GridUpdateHub>();
  hubContext.Clients.All.updateGrid(updatedData);

}
就是这样!通过这个实现,每当用户保存或更新数据时,SignalR集线器就会把更新后的数据发送给所有连接的客户端,ASPX页面中的JavaScript代码会处理接收到的更新,并为所有用户实时更新网格视图
快乐编码!!

相关问题