Click here to Skip to main content
15,895,256 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?

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;
}
 
Share this answer
 
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