Search code examples
c#winformstextboxcontrolsstring-concatenation

Combine 2 textbox text with delimiter


SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.Title = "Save Text File";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    string left = string.Format(EmailTxtbx.Text, Environment.NewLine);
    string right = string.Format(PasslTxtbx.Text, Environment.NewLine);
    string[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
    string[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

    string output = "";
    if (leftSplit.Length == rightSplit.Length)
    {
        for (int i = 0; i < leftSplit.Length; i++)
        {
            output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;
        }
    }

    using (StreamWriter bw = new StreamWriter(File.Create(path)))
    {
        textBox1.Text = output;
        bw.Write(output);
        bw.Close();
    }
}

Hey. I Have an issue. Lets Say I have 2 Textboxes I want The Textboxes Be Together:

TextBox1:

Test41
Test414
Test41

TextBox2:

Test55
Test56
Test54

TextBox3:

Test41:Test55
Test414:Test56
Test41:Test54

I want to load 2 files one to the first textbox and for the second textbox and combine With delimiter like ":" I Tried This Code And Its Not working. I'm new on c#.

Hope Someone Can Help Me


Solution

  • I’ll start from scratch. I have 2 textbox. In the first textbok it’s the mails. In the second textbox it’s passwords. What I need to do to combine the textboxes with “:”

    Try this code snippet:

        var txt1 = textBox1.Lines.Where(a => !string.IsNullOrEmpty(a)).ToArray();
        var txt2 = textBox2.Lines.Where(b => !string.IsNullOrEmpty(b)).ToArray();
        var txt3 = "";
    
        for(int i = 0; i < txt1.Length; i++)
        {
            if (i < txt2.Length)
                txt3 += $"{txt1[i]}:{txt2[2]}{Environment.NewLine}";
            else
                txt3 += $"{txt1[i]}{Environment.NewLine}";
        }
    
        textBox3.Text = txt3;
    

    Good luck.