【问题标题】:C# Data Grid ViewC# 数据网格视图
【发布时间】:2011-10-14 22:42:23
【问题描述】:

我有下面的代码,我ping一个网址指定的次数,每次将ping时间添加到一个名为resultsList的数组中。

然后我想将 resultsList 设置为我的数据网格视图的数据源。

正在使用 ping 值填充结果列表。

但是,它只是用 2 填充了我的数据网格视图。

有什么想法吗?

using System;
using System.Collections.Generic;
using System.Net;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace Ping_Application
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void pingButton_Click(object sender, EventArgs e)
        {
            List<string> resultsList = new List<string>();
            for (int indexVariable = 1; indexVariable <= timesToPing.Value; indexVariable++)
            {
                string stat = "";
                Ping pinger = new Ping();
                PingReply reply = pinger.Send(pingAddressTextBox.Text);
                if (reply.Status.ToString() != "Success")
                    stat = "Failed";
                else
                    stat = reply.RoundtripTime.ToString();
                pinger.Dispose();
                resultsList.Add(stat);
            }
            resultsGrid.DataSource = resultsList;
        }
    }
}

非常感谢, J

【问题讨论】:

  • “但是它只是用 2 填满了我的数据网格视图。”你的意思是2行吗?还是用数字 2?
  • 只有数字 2 - 重复了很多次,我运行了我的 Ping。与我将数据传递到数据网格视图的方式有关吗?
  • 首先,您需要一个 resultsGrid.DataBind() 来显示数据。如果没有,请将其放在 .DataSource 行之后。
  • 你能发布数据网格标记吗?

标签: c# winforms datagridview


【解决方案1】:

您正在绑定到每个字符串的长度。 您可以使用 DataTable 而不是列表:

DataTable resultsList = new DataTable();
resultsList.Columns.Add("Time", typeof(String));
...
resultsList.Rows.Add(stat);

还有其他方法,但我认为这是最简单的,您可以为列命名,并在需要时添加其他内容。

【讨论】:

    【解决方案2】:

    如果您使用的是 .NET framework 3.5 或 4.0,您可以在 system.Linq 中添加 using 子句并执行以下操作:

    resultsGrid.DataSource = resultsList.Select(x => new { Value = x }).ToList();
    

    或者,您可以使用字符串包装类:

    public class StringWrapper
    {
        public StringWrapper(string s)
        {
            Value = s;
        }
        public string Value { get { return _value; } set { _value = value; } }
        string _value;
    }
    

    然后你像这样声明你的变量:

    List<StringWrapper> resultsList = new List<StringWrapper>();
    

    然后你添加这样的项目:

    resultsList.Add(new StringWrapper(stat));
    

    然后你就可以绑定数据了,然后就可以了:

    resultsGrid.DataSource = resultsList;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      相关资源
      最近更新 更多