-1

I have form:

http://i.imgur.com/f7Af6Qz.png

and a csv file containing these values:

110977,3871933,317731,0,

How would I be able to copy the CSV data and paste it into all the correct fields in one copy and paste action? (All the data will be in the correct order)

Thanks in advance!

TeaAnyOne
  • 477
  • 1
  • 9
  • 16
  • Is this winforms or wpf? Please [edit] the correct tag in your question. Also consider adding an [mcve] so we can see where you're stuck. – rene Dec 04 '15 at 16:16
  • So, what happens currently when you paste the CSV data (where from, and in what format does it end up in your textbox)? Should it also happen if the user types in a comment? Simply responding to the `TextChanged` event and splitting on comma would suffice. – CodeCaster Dec 04 '15 at 16:26
  • 1
    Read CSV file, split via comma, assign each value from the resulting `string[]` to the appropriate `TextBox`, done. Which one of those do you have a specific question about? – Michael McGriff Dec 04 '15 at 16:27
  • @Michael that was my first reaction too, but it looks like OP is talking about a user pasting CSV-formatted data into the textboxes. If possible, I would read the file from the program instead as well, but not sure if that's what OP is after. – CodeCaster Dec 04 '15 at 16:32
  • @TeaAnyOne you can check my answer below, I modified it with the sample code for the case you need. – Dawid Sibiński Dec 04 '15 at 17:21

2 Answers2

2

I would suggest reading the CSV file by opening it, then split by comma, put your values into the string array and then update your textBoxes. Refer to the answer to this question. You can also use OpenFileDialog to provide the UI for opening the file.

EDIT:

I prepared some basic example to handle exactly the case you asked for. It assumes you have 4 values in the copied CSV line separated by comma (anyway if you have more than 4 in copied line just first 4 will be put into textBoxes). It only requires to copy the CSV line and paste it using Ctrl + V into the first textBox (txtValue1) so it is then splitted by , and all those values from copied CSV line are put into corresponding textBoxes (txtValue1, txtValue2, txtValue3, txtValue4 consecutively).

My form looks just like that:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            txtValue1.KeyDown += TxtValue1_KeyDown;
        }

        private void TxtValue1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.V)
            {
                string csvLine = Clipboard.GetText();
                if (String.IsNullOrEmpty(csvLine))
                    return;
                string[] values = csvLine.Split(',');

                if (values.Count() < 4)
                    return;

                txtValue1.Text = values[0];
                txtValue2.Text = values[1];
                txtValue3.Text = values[2];
                txtValue4.Text = values[3];

                e.SuppressKeyPress = true;
            }
        }
    }

It could of course be made more generic and handle possible exceptions. This is only to show how to solve what you need easily.

Community
  • 1
  • 1
Dawid Sibiński
  • 1,657
  • 3
  • 21
  • 40
  • _"split by comma"_ - that is not how you read CSV. CSV data can contain quoted commas. Yeah, the current example does not, but the next version will, and then your fragile code will break. Use a CSV parsing library. Do not reinvent the wheel poorly. – CodeCaster Dec 04 '15 at 16:41
  • Why not? In most cases you know what is the separator used in your CSV file, so you can just split by it. Of course in businesslike cases I would implement some CSV models classes and make it configurable (i.e. allowing to set the separator), however in simple cases if you are sure about the separator (and there are no delimiters in csv) I don't see the point of not reading it that way. – Dawid Sibiński Dec 04 '15 at 16:44
  • _"if you are sure about the separator"_ - you never are. Next week the requirement comes in to _also_ support semicolon or tab separated files. Don't advise to use fragile code unless the OP explicitly mentions that they don't care about maintainability. Do it right from the start: use library code for non-trivial tasks. Anyway OP is not talking about parsing a CSV file, it's about a user pasting a comma-separated value in one textbox. – CodeCaster Dec 04 '15 at 16:46
  • User has just provided the CSV sample so I wanted to provide him with the simplest solution. However I agree with you we should use library code when possible. Anyway, to implement some more flexible or abstract mechanism to parse CSV you need to know how it works underneath, as it always bases on splitting somehow. "Next week the requirement comes in to also support semicolon or tab separated files" - that's interesting, it comes for CSV standard? I've already seen many times so called "CSV" files, but splitted by semicolon, tabs or even with constant columns lengths as a "splitters". – Dawid Sibiński Dec 04 '15 at 16:54
  • There is no true CSV standard ([well, there is one, but nobody adheres to it](https://tools.ietf.org/html/rfc4180)), hence the use for libraries to detect and correct all edge cases. Anyway if you could provide some relevant code and mention that it only supports the shown case, it'd be really helpful. – CodeCaster Dec 04 '15 at 16:56
  • I modified my answer. That is the simplest solution for what user requests for. Of course assuming that this CSV copied line would always be structured the same. – Dawid Sibiński Dec 04 '15 at 17:11
0

Copy/Pasting? More like reading CSV from a stream ?

Create a Model aka a class to store the values once you start reading the CSV using any sort of stream reader. As you read the positions of the fields from the CSV you can start storing them into your model and then it is easy from there. You might want to think about reading everything into a List, so you only read once.

Here is your class

public class Model
{
    public string InvoiceNumber { get; set; }
    ...
}

Here is the CSV reading piece

        using (StreamReader sr = new StreamReader(sourceFileName))
        {
            List<Model> modelList = new List<Model>();
            string headerLine = sr.ReadLine();
            string currentLine;
            for (int i = 0; i < strArray.Length; i++)
            {       
                while ((currentLine = sr.ReadLine()) != null)
                {
                 string[] strArray = currentLine.Split(',');
                 Model myModel = new Model();

                 switch (i)
                    {
                        case 0: myModel.InvoiceNumber =  = strArray[i]; break;
                        case 1: myModel.InvoiceHeaderId = strArray[i]; break;
                    }
                }
            }
         modelList.Add(myModel);
        }

        }

From Here you can assign this to the UI.It depends which row you want to read, maybe filter the result to get the id, or filter my other pieces of data. Up to you to decide, you can add those filters in the for each loop. Or even better, take a look at LINQ. :D

foreach (var item in modelList)
{
    txtInvoiceNumber.Text = mymodel.InvoiceNumber;
    txtinvoiceHeaderId.Text = mymodel.InvoiceHeaderId;


}
JeffJeffery
  • 155
  • 1
  • 9