Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
4.80/5 (2 votes)
See more:
Hello Please can anyone help how to get data from .CSV file into DataGrid using WPF Button_Click, C#, i searchen online and found below code ,problem is that i can only first Column data only , where is wrong in this code, thanks in advance

C#
private void CsvLoad_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                lFnLoadFileData();
            }
            catch (Exception)
            {
                throw;
            }

            
        }
        void lFnLoadFileData()
        {
            try
            {
                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)
                {
                    // FileStream lObjFileStream = lObjFileDlge.File.OpenRead();
                    StreamReader lObjStreamReader = new StreamReader(fName);
                    System.Windows.MessageBox.Show(lObjStreamReader.ToString());
                    lFnGenerateData(lObjStreamReader);
                    lObjStreamReader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
             
}

       void lFnGenerateData(StreamReader aReader)
        {
            try
            {
                bool lBlnIsColumns = true;
                string[] lArrCols = null;
                Dictionary<string,> lObjDicData = null;
                ObservableCollection<dictionary><string,>> lArrDGRows = new ObservableCollection<dictionary><string,>>();
                 dataGrid1.Columns.Clear();
                while (aReader.Read() != 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;
                    int lIntColID = 0;
                    lObjDicData = new Dictionary<string,>();
                    foreach (string lStrCell in lArrStrCells)
                    {
                        lObjDicData[lArrCols[lIntColID]] = lStrCell.Trim();
                        lIntColID++;
                    }
                    lArrDGRows.Add(lObjDicData);
                }
                aReader.Close();
                dataGrid1.ItemsSource = lArrDGRows;

            }
            catch (Exception)
            {
                throw;
            }
        }
Posted
Updated 20-Jun-12 23:27pm
v2
Comments
Jim Jos 21-Jun-12 5:57am    
What is the delimiter.. Normally CSV files will have a comma (,) delimiter.. you have used a semi-colon here as delimiter..
getanswer 21-Jun-12 6:00am    
For my file i used (';') delimiter not (,). am getting First Column data ,but not all Columns data, thanks
Jim Jos 21-Jun-12 6:01am    
Could you put couple of rows of csv file I ll run it thru your code
getanswer 21-Jun-12 6:08am    
ID; FirstName; LastName; Address


1; Rajesh; kumar; Bombay

2; Firdaus; Alam; Delhi

3;Govind; Raj; Bangalore


4;Krishna; Rao; Kolkatta

You have a read() in the while loop which crates problems for you when you do readline()

Instead of areadr.read().. I have changed to areader.peek().. Now the rows are getting read but the observablecollection and Dictionary is too complex for the datagrid to display the rows you need to work on that..

Instaed you could use a custom object collection as list..

the custom class

C#
class PersonalInfo
       {
           public string ID { get; set; }
           public string FirstName { get; set; }
           public string LastName { get; set; }
           public string Address { get; set; }
       }


C#
The modified code

void lFnGenerateData(StreamReader aReader)
        {
            try
            {
                bool lBlnIsColumns = true;
                string[] lArrCols = null;
                List<PersonalInfo> lstPersonalList = new List<PersonalInfo>();
                dataGrid1.Columns.Clear();
                while (aReader.Peek() > 0)
                {
                    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;
                   
                    int lIntColID = 0;
                    PersonalInfo objPersonalInfo = new PersonalInfo();
                    objPersonalInfo.ID = lArrStrCells[0];
                    objPersonalInfo.FirstName = lArrStrCells[1];
                    objPersonalInfo.LastName = lArrStrCells[2];
                    objPersonalInfo.Address = lArrStrCells[3];

                    lstPersonalList.Add(objPersonalInfo);
                }
                aReader.Close();
                dataGrid1.ItemsSource = lstPersonalList;
 
            }
            catch (Exception)
            {
                throw;
            }
        }
 
Share this answer
 
v2
Comments
getanswer 21-Jun-12 7:38am    
Hi JimJos, is there any other way without using Observable collectins in this program, please let me know . thanks
getanswer 21-Jun-12 8:29am    
Thank you very much , this answer is suited for my question,JimJos you are great
getanswer 24-Aug-12 3:31am    
Hello ,please help me in above example public Enum { get; set; },

what should be here, PersonalInfo objPersonalInfo = new PersonalInfo();
objPersonalInfo.Enum = lArrStrCells[0];

how to convert String to Enum , thanks in advance
Jim Jos 27-Aug-12 9:19am    
Could you explaing you want a Enum variable in the object is it? What type of Enum values you want to assign? just give me three samples
getanswer 27-Aug-12 9:36am    
enum Enum{one=1,two=2,three=3}, should be display in first column of datagrid

thanks
Hi I have add solution in C# .
string delimStr = ";;" use deliminator as in your .CSV file
C#
public DataTable FromCsv()
    {
        string delimStr = ";;";
        char[] delimiter = delimStr.ToCharArray();
        string strFilePath = "D:\\kk\\pixpro_feed_v2_gb_en_full_hdr_20120501073002.csv";        
        DataSet oDS = new DataSet();
        string strFields = null;
        DataTable oTable = new DataTable();
        DataRow oRows = null;
        Int32 intCounter = 0;
        oDS.Tables.Add("Property");        
        StreamReader oSR = new StreamReader(strFilePath);
        //Go to the top of the file
        oSR.BaseStream.Seek(0, SeekOrigin.Begin);
        //Add in the Header Columns        
        foreach (string strFields_loopVariable in oSR.ReadLine().Split(delimiter))
            {
                strFields = strFields_loopVariable;
                oDS.Tables[0].Columns.Add(strFields);
            }
       //String request = oSR.ReadToEnd();
        //Now add in the Rows
        oTable = oDS.Tables[0];
        while ((oSR.Peek() > -1))
        {
        
                 oRows = oTable.NewRow();
            foreach (string strFields_loopVariable in oSR.ReadLine().Split(delimiter))
            {
                strFields =Convert.ToString( strFields_loopVariable);
                if (intCounter < 20)
                {
                    oRows[intCounter] = strFields;
                    intCounter = intCounter + 1;      
                }
                else
                {
 
                }
            }
            intCounter = 0;
            oTable.Rows.Add(oRows);
        }
        return oTable; 
    }
 
Share this answer
 
v2
Comments
getanswer 21-Jun-12 7:55am    
Hi Kamalakanth , thanks for your code, but can you explain me in WPF Button_CLick how it helpful using DataGrid, because in DataGrid no option to select Rows. thanks
 
Share this answer
 
Comments
getanswer 21-Jun-12 7:54am    
Hi Ragamayura, am doing in DataGrid please, this link not helping me to get exact answer but its helpful for me, thanks

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