我正在创建一个winform,它可以从另一个winform中读取数据,但我的函数中出现了一些错误:
namespace stackkcw
{
public partial class Form1 : Form
{
public TcpClient client;
private object datgdStock;
private object lablUpdates;
private object lablTime;
private int countOfData;
public Form1()
{
InitializeComponent();
}
private void UpdateGrid(StockDetails data)
{
datgdStock.Rows[data.StockId].Cells[0].Value = data.StockName;
datgdStock.Rows[data.StockId].Cells[1].Value = data.StockPrice;
datgdStock.Rows[data.StockId].Cells[2].Value = data.StockChange;
}
private void UpdateLbl(StockDetails data)
{
countOfData++;
lablUpdates.Invoke(new Action(() => lablUpdates.Text = countOfData.ToString()));
lablTime.Invoke(new Action(() => lablTime.Text = data.Time.ToString()));
}
private void button1_Click(object sender, EventArgs e)
{
DataReceiver data = new DataReceiver();
data.connect(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));
// Pass input in txtIP as an IPAddress and the input in txtPort as an int.
button1.Enabled = false; // Disable button connect on valid data sending to data reciever class.
textBox1.Enabled = false; // Disable ip text box on valid data sending to data receiver class
textBox2.Enabled = false; // disable port text box on valid data sending to data receiver class
data.dataRecieved += new DataReceiver.DataRecived(UpdateGrid);
data.dataRecieved += new DataReceiver.DataRecived(UpdateLbl);
}
public struct StockDetails
{
public int StockId;
public string StockName;
public double StockPrice;
public double StockChange;
public DateTime Time;
}
class DataReceiver
{
public delegate void DataRecived(StockDetails stockData);
public event DataRecived dataRecieved;
StockDetails data;
private TcpClient StockClient;
private Thread listeningThread = null;
public void connect(IPAddress ip, int port)
{
StockClient = new TcpClient();
StockClient.Connect(ip, port);
MessageBox.Show("Connected to: " + ip.ToString());
listeningThread = new Thread(new ThreadStart(listen));
listeningThread.Start();
}
public void listen()
{
NetworkStream stream = StockClient.GetStream();
while (true)
{
byte[] buffer = new byte[256];
int no_of_bytes = stream.Read(buffer, 0, 256);
JavaScriptSerializer Serializer = new JavaScriptSerializer();
data = Serializer.Deserialize<StockDetails>(Encoding.ASCII.GetString(buffer, 0, no_of_bytes));
OnDataRecived();
}
}
protected virtual void OnDataRecived()
{
dataRecieved(data);
}
}
}
}
答案 0 :(得分:0)
D不对这些属性使用对象
private DataGridView datgdStock;
private TextBox lablUpdates;
private TextBox lablTime;