0

I'm having trouble to transfer Information from Class' Method to Form's DataGridView.

My class has the following code:

public virtual void position(string account, Contract contract, double pos, double avgCost)
        {
            Console.WriteLine("Position. " + account + " - Symbol: " + contract.Symbol + ", SecType: " + contract.SecType + ", Currency: " + contract.Currency + ", Position: " + pos + ", Avg cost: " + avgCost);
            string text = account + "|" + contract.Symbol + "|" + contract.SecType + "|" + contract.Currency + "|" + pos + "|" + avgCost;
            myform.AddItemToDataGridView(text);
        }

And my Form has:

    public void AddItemToDataGridView(string text)
    {
        // See if a new invocation is required form a different thread
        if (this.dataGridView1.InvokeRequired)
        {
            SetTextCallback h = new SetTextCallback(AddItemToDataGridView);
            this.Invoke(h, new object[] { text });
        }
        else
        {
            dataGridView1.ColumnCount = 6;
            dataGridView1.Columns[0].Name = "Account";
            dataGridView1.Columns[1].Name = "Symbol";
            dataGridView1.Columns[2].Name = "Security Type";
            dataGridView1.Columns[3].Name = "Currency";
            dataGridView1.Columns[4].Name = "Position";
            dataGridView1.Columns[5].Name = "Average Cost";

            // What should i add here to break down my string into the right columns?

        }
    }

Can someone help me to break down that string in to right columns? There should be much better ways to do this. However, I cant get them to work

HEWhoDoesn'tKnow
  • 347
  • 3
  • 14
shiny
  • 171
  • 4
  • 13
  • 1
    `text.Split('|')` sould give you a string array. In `AddItemToDataGridView` you should add a new row for the DataGrid and populate with the results of the array, but I can't help you if I don't know what are you using for your UI. Ist it Windows Forms, WPF or something else? – ikerbera Nov 13 '18 at 07:08
  • Window Form. Ill try it – shiny Nov 13 '18 at 07:10
  • 1
    If is windows forms this [link](https://stackoverflow.com/questions/10063770/how-to-add-a-new-row-to-datagridview-programmatically) will be helpful. – ikerbera Nov 13 '18 at 07:12
  • string[] row1 = text.Split('|'); dataGridView1.Rows.Add(row1); – shiny Nov 13 '18 at 07:25
  • 2
    how about to encapsulate string values in class and pass it to gridView datasource ? no need to set columns name multiple times , one time is enough – Z.R.T. Nov 13 '18 at 07:30
  • That sounds super cool, could you give an example on how to do that? – shiny Nov 13 '18 at 07:36
  • https://stackoverflow.com/questions/6473326/using-a-list-as-a-data-source-for-datagridview – Z.R.T. Nov 13 '18 at 07:38

0 Answers0