Windows Appln - datagridview binding problem with List<string>

Posted by Madhavi under C# on 8/16/2011 | Points: 10 | Views : 5950 | Status : [Member] | Replies : 4
HI

I am working in C# windows application . Datagrid view when binded with LIst><string> showing numbers 14, or 9, 12 like that.
In my requirement, user will type a letter in textbox , basing on that i will search for files in a specific path starting with that letter and populate datagrid view with matched filenames . For that i am using List <string> which will store all the file names.



System.IO.DirectoryInfo di = new System.IO.DirectoryInfo( mypath );
System.IO.FileInfo[] dirFiles = di.GetFiles(textBox1.Text.ToUpper() + "*.*"); // ex: a*.* all file names starting with a
List<string> list = new List<string>();
foreach (FileInfo fi in dirFiles)
{
list.Add(fi.ToString());
}
dataGridView2.DataSource = list;



i can see that list is populated with rows. But binding has got problem. datagridview is showing single digit numbers 9 and sometimes showing 14 like that. Kindly help me at what point i am doing mistake.

Thanks
Madhavi




Responses

Posted by: Dhirendra on: 8/17/2011 [Member] Starter | Points: 25

Up
0
Down
I would suggest you to use different approach..
create a new class mentioned below and make a generic list of that class
and bind that generic class list to datagrid
modified code
DirectoryInfo di = new System.IO.DirectoryInfo(@"D:\Temp");

FileInfo[] dirFiles = di.GetFiles(textBox1.Text.ToUpper() + "*.*"); // ex: a*.* all file names starting with a
List<FileClass> list = new List<FileClass>();
foreach (FileInfo fi in dirFiles)
{
list.Add(new FileClass(fi.Name));
}
dataGridView1.DataSource = list;

Create a new class
class FileClass
{
public FileClass(string strFilename )
{
FileName = strFilename;
}
public string FileName { get; set; }
}

Madhavi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dhirendra on: 8/17/2011 [Member] Starter | Points: 25

Up
0
Down
there is another simple solution using lamda expression..
using this below line instead
dataGridView2.DataSource = list;

use this..
dataGridView1.DataSource = list.Select(x => new { Value = x }).ToList();

Madhavi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Madhavi on: 8/18/2011 [Member] Starter | Points: 25

Up
0
Down
Hi Dhirendra

Thanks a ton. Creating Class worked fine for me. Thanks once again.

I had another problem with drag and drop items from datagrid to desktop. will post soon. If u know pls help me


Cheers
Madhavi



Madhavi, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dhirendra on: 8/19/2011 [Member] Starter | Points: 25

Up
0
Down
please mark as answer if the above solution wroked for you............

Madhavi, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response