[英]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" 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 谢谢你们
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];
Based on your comments, you want to access "controls by name"; 根据您的评论,您想访问“按名称的控件”; this is accomplished with Controls.Find() : 这是通过Controls.Find()完成的:
Control ctl = this.Controls.Find(v1, true).FirstOrDefault();
if (ctl != null && ctl is TextBox)
{
TextBox tb = (TextBox)ctl;
tb.Text = v2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.