Winforms Listbox.DataSource由于某种原因无法正常工作

时间:2015-12-28 23:08:56

标签: c# winforms listbox

我有一个Listbox,我正在尝试为其设置DataSource 这应该是非常简单的

List<somekindaclass> list = new List<...>;
listBox.DataSource = list;

那不起作用。我四处搜索,发现了BindingSource

List<somekindaclass> list = new List<...>;
var bs = new BindingSource();
bs.DataSource = list;
listBox.DataSource = bs;

不幸的是,这也不起作用。

这是列表框的Designer.cs代码

    // 
    // clientsListBox
    // 
    this.clientsListBox.FormattingEnabled = true;
    this.clientsListBox.Location = new System.Drawing.Point(6, 19);
    this.clientsListBox.Name = "clientsListBox";
    this.clientsListBox.Size = new System.Drawing.Size(201, 225);
    this.clientsListBox.TabIndex = 4;
显然,一切都应该没问题,但事实并非如此。

我想我只是将表单代码倒在这里,你可能会发现什么是错的?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using ChatLibrary;

namespace ChatServer
{
    public partial class Server : Form
    {
        #region Private Members

        // Structure to store the client information
        private class Client
        {
            private bool Equals(Client other)
            {
                return Equals(endPoint, other.endPoint) && id.Equals(other.id) && Equals(data, other.data);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hashCode = endPoint?.GetHashCode() ?? 0;
                    hashCode = (hashCode * 397) ^ id.GetHashCode();
                    hashCode = (hashCode * 397) ^ (data?.GetHashCode() ?? 0);
                    return hashCode;
                }
            }

            public EndPoint endPoint;
            public Guid id;
            public PlayerData data;

            public override bool Equals(object obj)
            {
                if (ReferenceEquals(null, obj)) return false;
                if (ReferenceEquals(this, obj)) return true;
                return obj.GetType() == GetType() && Equals((Client)obj);
            }

            public override string ToString()
            {
                return string.Format("{0} : {1}", endPoint, data);
            }
        }

        // Listing of clients
        private List<Client> clientList;

        // Server socket
        private Socket serverSocket;

        // Data stream
        private byte[] dataStream;

        // Status delegate
        private delegate void UpdateStatusDelegate(string status);
        private UpdateStatusDelegate updateStatusDelegate;

        #endregion

        #region Constructor

        public Server()
        {
            InitializeComponent();
        }

        #endregion

        #region Events

        private void Server_Load(object sender, EventArgs e)
        {
            try
            {
                // Initialise the ArrayList of connected clients
                clientList = new List<Client>();

                var bs = new BindingSource { DataSource = clientList };

                clientsListBox.DataSource = bs;

                // Initialise the delegate which updates the status
                updateStatusDelegate = UpdateStatus;

                // Initialise the socket
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                dataStream = new byte[serverSocket.ReceiveBufferSize];

                // Initialise the IPEndPoint for the server and listen on port 30000
                IPEndPoint server = new IPEndPoint(IPAddress.Any, 30000);

                // Associate the socket with this IP address and port
                serverSocket.Bind(server);

                // Initialise the IPEndPoint for the clients
                IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);

                // Initialise the EndPoint for the clients
                EndPoint epSender = clients;

                // Start listening for incoming data
                serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, ReceiveData, epSender);

                lblStatus.Text = "Listening";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "Error";
                MessageBox.Show("Load Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region Send And Receive

        public void SendData(IAsyncResult asyncResult)
        {
            try
            {
                serverSocket.EndSend(asyncResult);
            }
            catch (Exception ex)
            {
                MessageBox.Show("SendData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {
                // Initialise a packet object to store the received data
                Packet receivedData = Packet.PacketFromBytes(dataStream);

                // Initialise the IPEndPoint for the clients
                IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);

                // Initialise the EndPoint for the clients
                EndPoint epSender = clients;

                // Receive all data
                serverSocket.EndReceiveFrom(asyncResult, ref epSender);

                var sendData = GetSendDataPacket(receivedData, epSender);

                // Get packet as byte array
                var data = sendData.ToByteArray();

                if (sendData.DataIdentifier != DataIdentifier.LogIn)
                {
                    foreach (Client client in clientList)
                    {
                        if (client.endPoint != epSender)
                        {
                            // Broadcast to all logged on users
                            serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, client.endPoint, SendData, client.endPoint);
                        }
                    }
                }

                // Listen for more connections again...
                serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, ReceiveData, epSender);

                // Update status through a delegate
                Invoke(updateStatusDelegate, sendData.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ReceiveData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private Packet GetSendDataPacket(Packet receivedData, EndPoint epSender)
        {
            Packet dataPacket = new Packet
            {
                DataIdentifier = receivedData.DataIdentifier,
                Name = receivedData.Name
            };

            ProcessMessageData(receivedData, epSender, dataPacket);

            return dataPacket;
        }

        private void ProcessMessageData(Packet receivedData, EndPoint epSender, Packet dataPacket)
        {
            Client sendingClient = clientList.FirstOrDefault(c => c.endPoint.ToString() == epSender.ToString());

            switch (receivedData.DataIdentifier)
            {
                case DataIdentifier.Message:
                    HandleMessageIdentifier(receivedData, epSender, dataPacket, sendingClient);
                    break;

                case DataIdentifier.LogIn:
                    HandleLogInIdentifier(receivedData, epSender, dataPacket, sendingClient);
                    break;

                case DataIdentifier.LogOut:
                    HandleLogOutIdentifier(receivedData, epSender, dataPacket, sendingClient);
                    break;
            }
        }

        #endregion

        #region Identifier Handling Methods

        private void HandleLogOutIdentifier(Packet receivedData, EndPoint epSender, Packet dataPacket, Client sendingClient)
        {
            if (sendingClient == null)
            {
                HandleAlreadyLoggedOut(epSender, dataPacket);
                return;
            }

            dataPacket.Message = string.Format("-- {0} has gone offline --", receivedData.Name);
            clientList.Remove(sendingClient);
 //           clientsListBox.Items.Remove(sendingClient);
        }

        private void HandleLogInIdentifier(Packet receivedData, EndPoint epSender, Packet dataPacket, Client sendingClient)
        {
            if (sendingClient != null)
            {
                HandleAlreadyLoggedIn(epSender, dataPacket);
                return;
            }

            Client newClient = new Client
            {
                endPoint = epSender,
                id = Guid.NewGuid(),
                data = Serializers.DeserializeObject<PlayerData>(receivedData.Message)
            };

            clientList.Add(newClient);
   //         clientsListBox.Items.Add(newClient);

            MessageBox.Show(
                string.Format("New player:\nEndPoint : {0}\nGuid : {1}\nData : {2}", newClient.endPoint, newClient.id,
                    newClient.data), "New Player Connected", MessageBoxButtons.OK, MessageBoxIcon.Information);

            dataPacket.Message = string.Format("-- {0} is online --", receivedData.Name);
        }

        private static void HandleMessageIdentifier(Packet receivedData, EndPoint epSender, Packet dataPacket, Client sendingClient)
        {
            if (sendingClient == null)
            {
                HandleMessageRecievedFromUnknown(epSender, dataPacket);
                return;
            }

            sendingClient.data = Serializers.DeserializeObject<PlayerData>(receivedData.Message);
            dataPacket.Message = string.Format("{0}: {1}", receivedData.Name, sendingClient.data);
        }

        #endregion

        #region Error Handling Methods

        private static void HandleAlreadyLoggedOut(EndPoint epSender, Packet dataPacket)
        {
            var errorLogoutMessage = string.Format("Recieved LOGOUT message from a player that's not in the list: {0}",
                epSender);

            MessageBox.Show(errorLogoutMessage, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            dataPacket.Message = errorLogoutMessage;
        }

        private static void HandleAlreadyLoggedIn(EndPoint epSender, Packet dataPacket)
        {
            var errorLoginMessage = string.Format("Player already in list : {0}", epSender);
            MessageBox.Show(errorLoginMessage, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            dataPacket.Message = errorLoginMessage;
        }

        private static void HandleMessageRecievedFromUnknown(EndPoint epSender, Packet dataPacket)
        {
            var messageRecievedErrorMessage = string.Format("Recieved message from player that's not in the list : {0}", epSender);
            MessageBox.Show(messageRecievedErrorMessage, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            dataPacket.Message = messageRecievedErrorMessage;
        }

        #endregion

        #region Other Methods

        private void UpdateStatus(string status)
        {
            messagesTextbox.AppendText(status + Environment.NewLine);
        }

        #endregion
    }
}

这应该是客户端的服务器,应该从统一连接,未完成,只是试验东西。

2 个答案:

答案 0 :(得分:1)

将新播放器添加到列表后,您应调用BindingSource.ResetBindings以强制重新加载与BindingSource关联的控件

因此,在全局级别声明您的BindingSource

BindingSource bs = new BindingSource();

并致电

clientList.Add(newClient);
bs.ResetBindings(false);

当然,您需要在clientList更改的每个位置执行相同的操作。

答案 1 :(得分:1)

bool test = condition_1; if(teste){ //lines of code 1 } #ifdef expression_1 if(!(test) && condition_2){ //lines of code 2 } #endif 不需要。如果您希望绑定的UI(在您的情况下为BindingSource)对源列表的修改作出反应,请将ListBox替换为类似的BindingList<T>类,但支持更改通知。

List<T>

所有其他代码保持不变。