Please note:- I already have gone few links answered but they are leading to controls only. I can use objects easily to access into objects, no issues about that. Issue is with variables accessing at runtime. One is directing to variable, but I found it very tough and rigid one. So want to know any simple and easy way.
I have a requirement following:-
Scenario for eg:-
1. TextBox_mobile is a control object in aspx page
2. mobile is a variable stored in c# .cs file
3. I have a 135+ such controls in aspx page and want to store them in variables in .cs file on say submit button.
4. I have stored in a table having two fields control_objects and against it variable names
5. So when submitt is fired (click event) I want to run the assigning task with running a process to retriew control names and
variables names and assinging the values of control objects to appropriate variables.
For eg to more going in practical:-
// create a variable to store textbox control
string mobile = ""
// Text_mobile is a TextBox in aspx page
// A temporary variable to store variable in loop from table
string var_mobile = "mobile"; // Currently I am hard coding
// now I wish to use this var_mobile to make automatically assign the value into main variable
<<var_mobile>> = TextBox_mobile.Text.Trim();
//and backend it should be actually storing same in earlier mobile variabl
mobile = TextBox_mobile.Text.Trim();
Since I have lot of objects and variables and later to work on variables, I want this to do in a loop like logic at a time instead of assigning them at individual basis.
Is there any such possible in Asp.net C#?
In c# this and all things which require code to interact with data about types and their members declared within assemblies can be achieved using reflection .
To get field using string containing its name you can use method GetField
and then call SetValue
on FieldInfo
returned by GetField
.
For example, if you have class named MyClass
declared like this
class MyClass
{
public int myField = 0;
}
You could use following code to set value of myField
MyClass myClass = new MyClass();
string fieldName = "myField";
int valueToSet = 10;
typeof(MyClass).GetField(fieldName).SetValue(myClass, valueToSet);
As per Kacper prompt quick answer, I was able to resolve with his point to point resolution.
CommonClass.cs
public class CommonClass
{
public string mobile = "";
public CommonClass()
{
//
// TODO: Add constructor logic here
//
}
}
My code in.cs file:-
string mobile = "";
CommonClass obj_class = new CommonClass();
string fieldname = "mobile";
typeof(CommonClass).GetField(fieldname).SetValue(obj_class, TextBox_mobile.Text);
mobile = obj_class.mobile.Trim();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.