Home > Software design >  How to load array into datagridview in c# the right way?
How to load array into datagridview in c# the right way?

Time:11-29

I am trying to load an array into datagridview , array is being populated by reading a csv file , everything works fine, but I am a bit confused about how I can break the array further and load each individual value inside a cell ? Right now its loading an entire line into one cell, so what will be the right way to further break the array and save each individual value into a cell ?

this is the code I am working with :

public void Load()
        {
            using (StreamReader sr = new StreamReader("Accounts.csv"))
            {
                string strResult = sr.ReadToEnd();
                string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            }
            dataGridView1.Columns.Add("Account#", "Account#");
            dataGridView1.Columns.Add("Passwor", "Password");
            dataGridView1.Columns.Add("Server", "Server");
            for (int i = 0; i < result.Length; i  )
            {
                dataGridView1.Rows.Add(new object[] { i   1, result[i] });
            }

        }

This is the output I am getting :

Image

And this is how the CSV file looks like :

Account#;Password;Server
2104373470;um3skuu;Rsptrsd
2104373472;uar1kgh;2jvatkf 
2104373475;6xuvtdp;ppjw5cj

CodePudding user response:

   change your code accordingly below.
     dataGridView1.Rows.Clear();


    for (int i = 0; i < result.Length; i  )
            {
                dataGridView1.Rows.Add ();
                dataGridView1.Rows [i].Cells ["Account"].Value = result[i].Split(';')[0];
  dataGridView1.Rows [i].Cells ["Password"].Value = result[i].Split(';')[1];
  dataGridView1.Rows [i].Cells ["Server"].Value = result[i].Split(';')[2];
                 }
  •  Tags:  
  • c#
  • Related