Set DataSource to DataGridView

N

NI-Student

Hi ...

I am a beginer of C# programing.
I want to show file list in a DataGridView.
So i coded like this.

grdFiles.AutoGenerateColumns = true;

OpenFileDialog openFile = new OpenFileDialog();

openFile.Multiselect = true;

if (openFile.ShowDialog() == DialogResult.OK)

{

files = openFile.FileNames;

grdFiles.DataSource = files;

}

NOTE: file is already define in top of the class as string[] file;

When i run this application, DataGridView Show only the length of the file in one coloumn.

I want to show the selected files list in a grid.

Please can anyone help me to solve this problem please...

Please.....
 
D

DabblerNL

Hi,

The problem is that the DataGridView not only wants to know what object to
read its data from, but also what field/property of that object to display.
By default it chooses the Length property. You would like it to display the
"Value" property or something, but unfortunately there is no way to tell the
dataGridView to display the actual strings in the array. The solution is to
create a wrapper class with a single property that returns the filename and
set an array of these wrappers as the datasource. Like this:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{

public partial class Form1 : Form
{
//this is the wrapper class
private class StringWrapper
{
public StringWrapper(string str)
{
FileName = str;
}

public string FileName { get; set; }
}
//

private StringWrapper[] strings;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//replace the code below to fill the strings array with the
filenames you retrieved.
strings=new StringWrapper[]{new StringWrapper("1"),
new StringWrapper("2"),
new StringWrapper("3"), };
//
this.dataGridView1.DataSource = strings;
// the dataGridView will now display the FileName property of
each element of the strings array
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top