Click here to Skip to main content
14,825,764 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to import .CSV file in DataGrid. Can anyone help where I am wrong?

Please look at my code below:
C#
private void button2_Click(object sender, RoutedEventArgs e)
{
    try
    {
        lFnLoadFileData();
    }
    catch (Exception ex)
    {
        System.Windows.MessageBox.Show("Input string was not in correct format ,select other file");
    }
}

void lFnLoadFileData()
{
    Microsoft.Win32.OpenFileDialog lObjFileDlge = new Microsoft.Win32.OpenFileDialog();
    lObjFileDlge.Filter = "CSV Files|*.csv";
    lObjFileDlge.FilterIndex = 1;
    lObjFileDlge.Multiselect = false;
    string fName = "";

    bool? lBlnUserclicked = lObjFileDlge.ShowDialog();
    if (lBlnUserclicked != null || lBlnUserclicked == true)
    {
        fName = lObjFileDlge.FileName;
    }
    if (System.IO.File.Exists(fName) == true)
    {

        StreamReader lObjStreamReader = new StreamReader(fName);

        lFnGenerateData(lObjStreamReader);
        lObjStreamReader.Close();
    }
}

void lFnGenerateData(StreamReader aReader)
{
    bool lBlnIsColumns = true;
    string[] lArrCols = null;
    List<details> lstPersonalList = new List<details>();

    dataGrid1.Columns.Clear();

    while (aReader.Peek() != null)
    {
        string lStrLine = aReader.ReadLine();
        if (lStrLine == null)
            break;
        if (lStrLine.Trim() == "")
            continue;
        string[] lArrStrCells = null;
        lArrStrCells = lStrLine.Split(';');
        if (lArrStrCells == null)
            continue;
        if (lBlnIsColumns)
        {
            lArrCols = lArrStrCells;
            foreach (string lStrCell in lArrStrCells)
            {
                DataGridTextColumn lDGCol = new DataGridTextColumn();
                lDGCol.Header = lStrCell;
                lDGCol.Binding = new System.Windows.Data.Binding(lStrCell);
                dataGrid1.Columns.Add(lDGCol);
            }
            lBlnIsColumns = false;
            continue;
        }

        if (lArrCols == null)
            continue;

        Details dt = new Details();
        dt.MyEnum= Enum.Parse(typeof(MyEnum),lArrStrCells[0]));
        dt.DataTyp = lArrStrCells[1];
        dt.Address = lArrStrCells[2];
        dt.Comment = lArrStrCells[3];
        lstPersonalList.Add(dt);
    }
    aReader.Close();
    dataGrid1.ItemsSource = lstPersonalList;
}

public class Details
{
    public enum MyEnum
    {
        one = 1,
        two = 2,
        three = 3
    }

    public MyEnum Value { get; set; }
    public string DataTyp { get; set; }
    public string Address { get; set; }
    public string Comment { get; set; }
}


thanks in advance
Posted
Updated 27-Aug-12 3:47am
v2
Comments
[no name] 27-Aug-12 9:43am
   
Instead of wanting someone to debug your code for you, how about trying to do it yourself?
getanswer 27-Aug-12 9:50am
   
my error is, input string was not in correct format, select other file, thanks
[no name] 27-Aug-12 9:53am
   
And? Debug it and find out why. You don't think that it's possible that it's failing because you are trying to parse a comma delimited file by using a semicolon do you?
getanswer 27-Aug-12 10:00am
   
thats not a problem with delimited, i took semi colon in my export file also
[no name] 27-Aug-12 10:04am
   
Okay so your file is not a CSV at all. Don't you think that is kind of need-to-know information?
[no name] 27-Aug-12 10:03am
   
That is your error message. Try finding out what the real error is.
getanswer 27-Aug-12 10:06am
   
i spend lot of time on this, if you know please tell me where am wrong, or let others help me,thanks
[no name] 27-Aug-12 10:11am
   
I am not stopping anyone else from helping you. Why should I spend my valuable time debugging something for you when you have not tried to do anything for yourself?
getanswer 27-Aug-12 10:13am
   
hey, read my answers then reply , thanks
[no name] 27-Aug-12 10:16am
   
Hey I did read your answers and reply. You have not told us what the actual problem is. YOUR error message does not tell us anything. You have to debug your code and find out what the real error message it. No one else can compiile your code to find out.
getanswer 27-Aug-12 10:20am
   
please leave me, thanks i think you dont know
[no name] 27-Aug-12 10:28am
   
Only because YOU are not providing the information that anyone would need to help you. Good luck, you are going to need it.
getanswer 27-Aug-12 10:29am
   
thanks for ur advice
ZurdoDev 27-Aug-12 10:13am
   
When you step through the code, which line is giving a problem?
getanswer 27-Aug-12 10:19am
   
public MyEnum Value { get; set; }, here is error
ZurdoDev 27-Aug-12 10:25am
   
So, that must mean that you are trying to set an invalid type, like a string to an int. What is the value of lArrStrCells[0]?
getanswer 27-Aug-12 10:28am
   
maybe i dont know how to convert string to enum, or enum to string here, thanks
ZurdoDev 27-Aug-12 10:31am
   
What is the value of lArrStrCells[0]?
getanswer 27-Aug-12 10:33am
   
this is the first column in DataGrid having enums ,

For example
public enum MyEnum
{
one = 1,
two = 2,
three = 3
}
ZurdoDev 27-Aug-12 10:36am
   
Yes, I know but when you debug what is the value of lArrStrCells[0]? I think that is not getting converted into your enum so what is its value?
getanswer 27-Aug-12 10:37am
   
am getting error here, there is no value in this point,
ZurdoDev 27-Aug-12 10:40am
   
If there is no value in lArrStrCells[0] then trying to parse that into an enum will clearly cause the error. lArrStrCells[0] needs to be 1, 2, or 3 but it needs to match. Or, am I missing something?
getanswer 27-Aug-12 10:41am
   
eactly , i want to parse enum to display in datagrid Binding with first column, i don't know where am wrong, am not getting this point
ZurdoDev 27-Aug-12 10:53am
   
I am not sure why we are struggling to understand each other. As I understand it, dt.MyEnum= Enum.Parse(typeof(MyEnum),lArrStrCells[0])); is failing. It is failing because you are trying to take the value in lArrStrCells[0] and convert it to either 1,2,or 3, which is your enum. But since the value is empty you can't convert empty to 1, 2, or 3. I can't tell you how to change your code because it is your code. You need a value in lArrStrCells[0].
getanswer 27-Aug-12 11:02am
   
HI the value is coming, lArrStrCells[0] is 'one', when i tried with dt.MyEnum= (MyEnum)Enum.Parse(typeof(MyEnum),lArrStrCells[0])
ZurdoDev 27-Aug-12 11:10am
   
OK, then that should work. But lArrStrCells[0] returns an object I believe and Enum.Parse() wants a string so just do lArrStrCells[0].ToString()
getanswer 27-Aug-12 11:18am
   
Hi, now the error os requested value 'one' not found
ZurdoDev 27-Aug-12 11:29am
   
You need to assign to Value in your Details class, not dt.MyEnum. Change to dt.Value and try. Value is the variable storing the enum value and MyEnum is the actual Enum.
getanswer 27-Aug-12 11:37am
   
now error is, "The value passed in must be an enum base or an underlying type for an enum,such as an Int32.Parameter name:value"

ZurdoDev 27-Aug-12 11:42am
   
Try putting (MyEnum) right before Enum.Parse(typeof(MyEnum),lArrStrCells[0])); so that you have (MyEnum) Enum.Parse(typeof(MyEnum),lArrStrCells[0]));
getanswer 27-Aug-12 11:45am
   
error is, requested value 'one' not found
ZurdoDev 27-Aug-12 12:50pm
   
I'm not seeing it. Here is a good sample, maybe look at it but from the code you posted I don't see it. http://www.dotnetperls.com/enum-parse

Also, is it still failing on the same line?
Kuthuparakkal 27-Aug-12 10:29am
   
see my solution... it's not DB, it's readinbg file using JET driver(available on .Net platform)
getanswer 27-Aug-12 10:34am
   
Hi, am using DataGrid in WPF, this may i get wrong some fields, thanks

1 solution

Why do you go with Stream Reader stuff and go through each and every column.

Let me explain a simplified approach:


C#
void PopulateGrid()
{
 Microsoft.Win32.OpenFileDialog lObjFileDlge = new Microsoft.Win32.OpenFileDialog();
    lObjFileDlge.Filter = "CSV Files|*.csv";
    lObjFileDlge.FilterIndex = 1;
    lObjFileDlge.Multiselect = false;
    string fName = "";
 
    bool? lBlnUserclicked = lObjFileDlge.ShowDialog();
    if (lBlnUserclicked != null || lBlnUserclicked == true)
    {
        fName = lObjFileDlge.FileName;
    }
   if (!System.IO.File.Exists(fName)) 
   return;
            this.SuspendLayout();
            DataGridView dataGrid1 = new DataGridView();
            dataGrid1.AutoGenerateColumns = true;
            dataGrid1.AllowUserToDeleteRows = true;
            dataGrid1.AllowUserToAddRows = true;
            dataGrid1.AllowUserToOrderColumns = true;
            dataGrid1.Height = 250;
            dataGrid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGrid1.ScrollBars = ScrollBars.Both;
            dataGrid1.Location = new System.Drawing.Point(10, 120);
            dataGrid1.DataSource =this.GetData(fName, true);
 
            this.Controls.Add(dataGrid1);
            this.ResumeLayOut();
 
}
 
public DataTable GetData(string path, bool firstRowHeader)
{
    if (!File.Exists(path))
        return null;
 
    string full = Path.GetFullPath(path);
    string file = Path.GetFileName(full);
    string dir = Path.GetDirectoryName(full);
 
    string withHeaderconnString = "Provider=Microsoft.Jet.OLEDB.4.0;"
     + "Data Source=\"" + dir + "\\\";"
     + "Extended Properties=\"text;HDR=Yes;FMT=Delimited\"";
 
    string NoHeaderconnString = "Provider=Microsoft.Jet.OLEDB.4.0;"
     + "Data Source=\"" + dir + "\\\";"
     + "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
 
    //create the "database" connection string
    string connString = NoHeaderconnString;
 
    if (firstRowHeader)
        connString = withHeaderconnString;
 
    //create the database query
    string query = "SELECT * FROM " + file;
 
    //create a DataTable to hold the query results
    DataTable dTable = new DataTable("Contacts");
    //create an OleDbDataAdapter to execute the query
    OleDbDataAdapter dAdapter =
       new OleDbDataAdapter(query, connString);
 
    try
    {
        //fill the DataTable
        dAdapter.Fill(dTable);
    }
    catch (InvalidOperationException /*e*/)
    { }
 
    dAdapter.Dispose();
 
    return dTable;
}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900