Click here to Skip to main content
14,735,239 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

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 21-Jun-12 0:27am
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

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


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;
            }
        }
   
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
Jim Jos 27-Aug-12 9:47am
   
YOu would like to use the ID field for that or a new field?
getanswer 27-Aug-12 9:51am
   
i would like to use enum filed instead of ID field, thanks
Jim Jos 27-Aug-12 9:55am
   
Enums you should use only for named fields like Blue, Red, and inside it will be represented as 1, 2.. but if you want just numbers displayed as row no.. you need to use an intger field.. please confirm you just want the number displayed in the datagrid?
getanswer 27-Aug-12 10:01am
   
i want string, not integer please, thanks
Jim Jos 28-Aug-12 1:33am
   
String value should be 1,2,3 etc is it.. ok.. lets work on that
getanswer 28-Aug-12 4:59am
   
ok, then let me know abou this please
Jim Jos 28-Aug-12 8:26am
   
right now what is being shown? You are not gettig any value from objPersonalInfo.ID = lArrStrCells[0]??
Hi I have add solution in C# .
string delimStr = ";;" use deliminator as in your .CSV file
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; 
    }
   
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
   
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