0

I'm trying to add values from TextBoxes to a DataTable so that I can check for null values (and later, duplicate values)

I am able to add Rows to the table directly from the TextBoxes, but when I try and dynamically add the last TextBox(es) my code is adding a String rather than the required Value as below:

            DataTable dt = new DataTable("CheckforNulls");
            dt.Columns.Add("ColumnToCheck", typeof(string));

            dt.Rows.Add(txtSettingsOneValue.Text.ToLower());
            dt.Rows.Add(txtSettingsTwoValue.Text.ToLower());

            //ComboBox that has a value between 1 and 12
            int x = int.Parse(cbSettingsThreeValue.SelectedItem.ToString());

            int i = 1;
            while (i <= x)
            {
                string threeValue = "txtSettingsThreeValue" + i + ".Text.ToLower()";

                dt.Rows.Add(threeValue);

                i++;
            }

At the moment my DataTable looks like below after running through

            ColumnToCheck
            V
            S
            txtSettingsThreeValue1.Text.ToLower()

Is there any way of converting the string to an Existing TextBox Name and then adding it to the Value of the TextBox to the DataTable?

2 Answers 2

2

You need to actually Find the control when it is required to use .Text property associated with control.

Problem lies here:

string threeValue = "txtSettingsThreeValue" + i + ".Text.ToLower()";

Find your control from From control collection, cast it as textbox and get access to Text property.

TextBox txtBox = (TextBox)this.Controls.Find("txtSettingsThreeValue" + i, false).FirstOrDefault();
string threeValue = txtBox.Text.ToLower();

If your control is nested inside some other controls then use true.

See the description on MSDN reference above.

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

Comments

1

find control by name :

private Control FindControlByName(string name)
{
    foreach (Control c in this.Controls) 
    {
       if (c.Name == name)
           return c; //found
    }
    return null; //not found
 }

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.