Massimo P.
Massimo P.

Reputation: 55

Set variables values whose name is passed by string in C#

I'm searching a method for setting dynamically the values of a list of variables whose names and values are readed from a database.

I've found a lot of code for getting the variable name and value, but nothing that works for setting the value.

I'll try to explain myself better. Think to have a database that contains two columns, say "name" and "value". Say for example that you have two records:

1) Name="string1", Value="message1" 2) Name="string2", Value="message2"

I have the code to read the two records, what i want is a way to take dinamically the names of the variables from the records and assign to them the corresponding values.

The code is this:

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();

    //Something here to assign the value stored in v2 to the variable whose name is stored in v1

}

Thank you all

Upvotes: 1

Views: 1322

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Based on your comments, you want to access "controls by name"; this is accomplished with Controls.Find():

Control ctl = this.Controls.Find(v1, true).FirstOrDefault();
if (ctl != null && ctl is TextBox)
{
    TextBox tb = (TextBox)ctl;
    tb.Text = v2;
}

Upvotes: 0

JuanR
JuanR

Reputation: 7783

I don't know why you would want to do this but why not just use a dictionary?

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
SqlDataReader dr = cmd.ExecuteReader();
var variables = new Dictionary<string, string>();
while (dr.Read())
{
    var v1 = dr["Name"].ToString();
    var v2 = dr[lng].ToString();
    variables.Add(v1, v2);
}

Then to use them:

var x= variables[v1];

Update:

I see you added a note saying you need to refer to objects. You could change the Dictionary to hold objects instead. You didn't mention the type so for argument sake I will assume they are all text boxes:

SqlCommand cmd = new SqlCommand("Select Name, " + lng + " from dbo.traductions", Global.languageconn);
    SqlDataReader dr = cmd.ExecuteReader();
    var variables = new Dictionary<string, object>();
    while (dr.Read())
    {
        var v1 = dr["Name"].ToString();
        var v2 = dr[lng].ToString();
        var textbox = new TextBox() { Text = v2 };
        variables.Add(v1, textbox);
    }

Then to use them by name:

var textbox= variables[v1];

Upvotes: 1

Related Questions