tags:

views:

28

answers:

2

I want to copy two columns from excel and work on them in a c# program. What component is the best to use to mimic an excel column in a win form?

+4  A: 

You can use the DataGridView control.

SLaks
I can't seem to copy a whole column at a time only single cells. Is that functionality possible?
Lumpy
Set the `SelectionMode` property to `CellSelect`.
SLaks
I set selection mode to CellSelect but still can't paste into the data grid and create new rows
Lumpy
`DataGridView` does not have built-in support for pasting multiple cells. You'll need to parse the TSVs from the clipboard yourself.
SLaks
+3  A: 

You could write a routine that pulls in clipboard data with something like:

    private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // create dataset to hold csv data:
        DataSet ds = new DataSet();
        ds.Tables.Add();
        ds.Tables[0].Columns.Add();
        ds.Tables[0].Columns.Add();
        ds.Tables[0].Columns.Add();
        ds.Tables[0].Columns.Add();
        ds.Tables[0].Columns.Add();
        ds.Tables[0].Columns.Add();

        string[] row = new string[1];

        // read csv data from clipboard
        IDataObject t = Clipboard.GetDataObject();
        System.IO.StreamReader sr =
                new System.IO.StreamReader((System.IO.MemoryStream)t.GetData("csv"));

        // assign csv data to dataset      
        while (!(sr.Peek() == -1))
        {
            row[0] = sr.ReadLine();
            ds.Tables[0].Rows.Add(row);
        }

        // set data source
        dataGridView1.DataSource = ds.Tables[0];
    }

Cleaned up code and tested code sample. It is still rough but demonstrates the capability with a fixed number of columns. (Pasting in more than six will crash, any less should work.)

Paul Sasik