JHarley1
JHarley1

Reputation: 2112

C# Data Grid View

I have the below code, I am pinging a web address for a specified number of times, each time adding the ping time to an array called resultsList.

I then want to set resultsList as the data source for my Data Grid View.

The resultsList is being populated with ping values.

However it simply fills up my Data Grid View with 2's.

Any ideas?

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;
        }
    }
}

Many Thanks, J

Upvotes: 1

Views: 3563

Answers (2)

GianT971
GianT971

Reputation: 4523

If you are using .NET framework 3.5 or 4.0, you can add a using clause to system.Linq and do the following:

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

Or, you can use a string wrapper class:

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

Then you declare your variable like this:

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

And you add items like this:

resultsList.Add(new StringWrapper(stat));

Then you can bind the data, and there you go:

resultsGrid.DataSource = resultsList;

Upvotes: 2

Steve Wellens
Steve Wellens

Reputation: 20638

You are binding to the length of each string. You can use a DataTable instead of a list:

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

There are other ways, but I think this is simplest and you can name the column and you can add other stuff when you need to.

Upvotes: 2

Related Questions