从字符串获取控件名称,然后使用ControlName.Text添加到数据表 [英] Getting Control Name from String and then use ControlName.Text to add to datatable

查看:101
本文介绍了从字符串获取控件名称,然后使用ControlName.Text添加到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将TextBoxes中的值添加到DataTable中,以便可以检查空值(以及以后的重复值)

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

我可以添加直接从TextBoxes到表的行,但是当我尝试动态添加最后一个TextBox时,我的代码添加的是String而不是所需的值,如下所示:

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++;
            }

目前,我的DataTable经过运行后如下所示

At the moment my DataTable looks like below after running through

            ColumnToCheck
            V
            S
            txtSettingsThreeValue1.Text.ToLower()

有什么方法可以将字符串转换为现有TextBox名称,然后将其添加到DataTable的TextBox值中?

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?

推荐答案

您实际上需要在需要使用 .Text c>与控件关联的属性。

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

问题在这里:

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

从控件集合中找到您的控件

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

如果您的控件嵌套在其他控件中,请使用 true

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

请参阅上面有关MSDN参考的说明。

See the description on MSDN reference above.

这篇关于从字符串获取控件名称,然后使用ControlName.Text添加到数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆