I have a C# Form that prints multiple instances of a User Control. Let's say that the form prints 5 instances of the User Control (Please see the link attached). How can I store/save the data inputted in all User Controls? Thanks
Here is the screenshot of the C# Form:
You'll have to store the User Controls when you instantiate them in a List or something.
You could have a class like this:
class SomeUC : UserControl
{
public SomeUC()
{
}
// A public method.
public string GetData()
{
return textBox1.Text;
}
}
Where textBox1 is the Name of a TextBox in your SomeUC
And then inside your main or something.
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();
// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);
Add as much as you want.
A List is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List.
And then you can access them from the list by their index.
SomeUC uc1 = list[0];
string data = uc1.GetData();
This is an example of accessing one control (the TextBox) in your SomeUC. For other classes (such as the ComboBox) the interaction is different. Meaning you won't have a Text property in the ComboBox. You'll have to figure out things like that on youself. A little research is what it takes. You can always come back if you couldn't find a solution for something.
You can create a property like this for each item in user control.
public string DG
{
get
{
return txtDG.Text;
}
set
{
txtDG.Text = value;
}
}
Then you can access the control value by using following line in your form.
supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP).
To get value from control
string DG = ((MyControl)pnlFLP.Controls[0]).DG;
To set value in control
((MyControl)pnlFLP.Controls[0]).DG = "1";
Try this code for accessing user control in the page
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)
Related
I have two Forms in my application. A Form has the following fields: txtPower, txtTension and txtCurrent. I would like to access the values filled in these TextBox through another Form. In the second Form I instantiated an object of the first Form (MotorForm), however I do not have access to the TextBox.
public MacroForm()
{
InitializeComponent();
MotorForm motorForm = new MotorForm();
motorForm.Show();
}
Is there any way?
Please do not expose the controls in your form. Never. (Unless you have a really good reason.)
If the problem is simple enough not to use MVVM (or the like) in your program (which you should consider for every program that's but trivial), you should expose the values of the instantiated form via properties. Think
public string Power
{
get { return txtPower.Text; }
set
{
if(ValidatePower(value))
{
txtPower.Text = value;
}
else
{
// throw ??
}
}
}
If we can make a sensible assumption about the type of the value we could extend this to
public double Power
{
get
{
// parse the value
// validate the value
// throw if not valid ??
// return the value
}
set
{
// validate the value
// set the value in the text box
}
}
If you exposed the txtPower object, you'd make the instantiating class depend on implementation details of the instantiated class, which is virtually never a good thing.
It seems that your problem is a perfect situation for using ShowDialog for opening your form.
To accomplish this, you need to change the Modifiers property of the controls you want to access on MotorForm and set them to Public. And also set the DialogResult property of your form somewhere to a desired value i.e OK. Anyway the easier way to do this is to set it on the button that is supposed to close the form. Suppose OK or CANCEL buttons.
Then you can create your form this way:
MotorForm motorForm = new MotorForm();
if(motorForm.ShowDialog() == DialogResult.OK)
{
string myValue = motorForm.txtPower.Text; //you can access your values this way
}
I have a user control (ucMarket) which contains (for the purpose of simplicity) two controls: a ListBox (ucListBox) and a Label (ucLabel). I need to create multiple instances of that user control on the page dynamically (depending on the results from a DataSet), and I add them using a foreach statement and the following:
Panel1.Controls.Add(ucMarket1);
But how do I get access to the ListBox properties like Rows ? The only thing I have found so far is to cast the control as a ListBox:
ListBox listBox1 = (ListBox)ucMarket1.FindControl("ucListBox");
listBox1.Rows = 10;
For the Label part, I guess I can also do something similar:
label1 = (Label)ucMarket1.FindControl("ucLabel");
But then, how do I put that information back into the user control ? Is there a way to work directly with the user control instead of casting ?
Ok a couple of things. from a naming convention point of view, don't call the label & listbox, ucSOMETHING. This is very confusing and not clear from your example whether you're referring to the asp:Label control or some custom userControl you've written. As for accessing your controls.
I'm assuming you are creating and adding a bunch of user controls in the following manner.
for(int i = 0; i < 5; i++)
{
var control = Page.LoadControl("~/Path/To/ucMarket.ascx");
control.Id = "ucMarket" + i;
Panel1.Controls.Add(control);
}
So your best bet is to expose the Listbox on your Control as a public property.
public class ucMarket : UserControl
{
public ListBox TheListBox
{
get { return ucListBox; }
}
}
That way you could access your listbox in the following way.
var ctrl = Panel1.FindControl("ucMarket1") as ucMarket;
ctrl.TheListBox.Rows ;
I am storing name and last name in two labels in main page. I also have those values in a class (class doesnt do much but i am using them for future expansion). I have a user control that will send an email with name and last name as body.
My question is that how can I transfer label or class variable values into user control's body variable?
Create a property on your user control with the datatype of the data you want to pass to it, and populate it in your page on creation of the control.
public class myUserControl : Control
{
...
public int myIntProperty {get; set;}
...
}
Later this in the code behind you can assign the value like
myUserControl cntrl = new myUserControl();
cntrl.myIntProperty = 5;
Instead of this you can pass the value through Markup also like
<uc1:myUserControl ID="uc1" runat="server" myIntProperty="5" />
You need to create properties on your control to hold these values; then from the page code, simply assign the values to the properties in the control.
On your control, you can have something like
public string FirstName
{
get {
if (ViewState["FirstName"] == null)
return string.Empty;
return ViewState["FirstName"].ToString();
}
set {
ViewState["FirstName"] = value;
}
}
You need to define public properties on the control and then when you use control on the page you can pass values to those parameters.
Something like:
<cc:mycustomControl runat="server"
MyProperty1=<%# label1 %>
MyProperty2=<%# label2 %>
/>
Step 1:
You can expost the values as property and than you can make use of that easily.
Step 2: To access your page from the user control you can make use of Parent property or may be some custome login to access the parent page and than write code to consume the property value.
you can do something like this in your user control
string x=((yourparentcontrol)this.parent).label1.text;
and use the string x.
I have a WPF main window, which contains a toolbar with buttons and a tabcontrol that is displaying a page with a listbox. The page is hosted on a frame, and the frame is set on the tab I selected.
When I click on a button on my toolbar, a new window pops up with a textbox and a submit button. When I press the submit button, I want to insert the textbox contents into the listbox that's on the main window. However, nothing displays in the listbox. I tried listbox.Items.Add() but it still won't display.
public partial class AddNewCamper : Window
{
public AddNewCamper()
{
InitializeComponent();
}
private void btnNewSubmit_Click(object sender, RoutedEventArgs e)
{
CampersPage c;
// Converting string to int b/c thats what camper() takes in.
int NewAge = Convert.ToInt16(txtNewAge.Text);
int NewGrade = Convert.ToInt16(txtNewGrade.Text);
// Create a new person
Camper person = new Camper(NewAge, NewGrade, txtNewFirstName.Text);
txtNewFirstName.Text = person.getName();
// Trying to add the first name of the person to display on the listbox of another window.
c.testListBox.Items.Add(txtNewFirstName.Text);
}
You can follow any of the following approaches. But based on your comments I guess solution 3 suits you.
1) Try initializing c first. You can't use an object without allocating memory for it.
2) If you want to use the same object, use the reference of the object created in the MainWindow
in the required class.
something like this should work:
CampersPage c = [reference to CampersPage object in MainWindow]
then add items to your listbox
3) If you want to use the listbox object, make your CampersPage Class static.
Making it static would not require you to initialize your class explicitly.
public static CampersPage {
// do something here
}
Make sure that you declare your listbox in CampersPage as public.
Then in the class requiring your listbox defined in CampersPage, do the following
CampersPage.testListBox.Items.Add(txtNewFirstName.Text);
4) If the classes are in the same namespace, you can declare listbox as a global public property and access it from rest of the classes in the same namespace.
I have a dynamically created (runtime creation) textbox whose name is available as a string.What i want to do is access this textbox like we do as normal textboxes .Can any one tell me how to cast it as textbox or any other solution
If you know the name of the textbox and its parent controls, you can do like this:
TextBox tb = (TextBox )parent.Controls["name"];
In addition to Iordan's answer, if you don't know exactly where on your form the textbox is, then this extension method should help alot. Note, Form's inherit from Control somewhere down the track too, so you can call it from that, or any control on your form.
public static class ExtensionMethods
{
public static Control FindControl(this Control root, string name)
{
foreach (Control c in root.Controls)
{
// Check this control
if (c.Name == name) return c;
// Check this controls subcontrols
Control tmp = c.FindControl(name);
if (tmp != null) return tmp;
}
return null;
}
}
If this still isn't flexible enough for you, then you can iterate over System.Windows.Forms.Application.OpenForms
Since you seem to have control over the creation process, put a reference to it in a dictionary.
TextBox txt = DynamicCreate(name);
map[name] = txt;
this.Controls.Add(txt);
All you have to do is look it up in your dictionary, instead of loop through all the controls on the form.
TextBox txt = map["name"];