0

I have a button that will store the text value of 80 text boxes in winforms c#.

The button looks something like this at the moment

    private void btnSaveChanges_Click(object sender, EventArgs e)
    {
        //Create new connection to the MongoDB Database and select the database and "table"
        var nol = NetworkOpsLayer.NetworkOpsLayer.CreateForDirectMongoConnection("mongodb://snipip", "snipdbname", "snip");
        //Inser the document starting with the selected node name, id, timestamp and then the entire loan data
        nol.InsertDoc("{ \"LoanName\" : \"" + tvTodoList.SelectedNode.Name + "\", \"AgentName\" : \"" + txtAgentName.Text + "\" }");
    }

This approach will work but I will end up with a string that is very long. nol.InsertDoc("{long JSON string of keys and textboxIDs}") as 80 textbox values each with their JSON key will be contained inside the string.

I'm wondering if there is a better way to go about this? Would it be possible to still form a valid JSON string by looping through each textbox on the form and give it a key that relates to the textbox so it's identifiable inside the MongoDB database?

2
  • you can try to make one eventhandler for all textboxes, that store their value (when the text changes) in a dictionary<textbox, string>. with your save button, you can create your JSON with around 10 lines of code (loop over the dictionary) Commented Nov 10, 2016 at 11:35
  • 2
    If you are concatenating 80 textboxes, then you should use StringBuilder.Append to concatenate your string instead of + Commented Nov 10, 2016 at 11:40

1 Answer 1

1

You can loop through the controls pick out the names of the textboxes and the corresponding values like this:

List<string> textboxNames = new List<string>();
List<string> textboxValues = new List<string>();

foreach (var c in this.Controls)
{
    if (c is TextBox)
    {                   
        textboxNames.Add((c as TextBox).Name);
        textboxValues.Add((c as TextBox).Text);
    }
} 

What you do with those values is up to you :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.