Same control names on multiple forms

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 2850 Views - Last Post: 01 August 2008 - 12:24 PM Rate Topic: -----

#1 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Same control names on multiple forms

Posted 28 July 2008 - 12:09 PM

Hello all.

I'm attempting to develop a small program in C# but am running into a bit of a problem.

I have two forms, say Form1 and Form2 and I have a static function Func1.
Form1 and Form2 are completely different forms, but both have controls that are named the same. Let's say I have a:

Form1.Textbox1
Form1.Textbox2
Form2.Textbox1 and
Form2.Textbox2

Now here's my issue. I need Func1 to preform its task (let's say it clears textboxes or something) on the form that is passed to it. When I originally wrote Func1, I only had one form, so the code looked a little like this.

public static void Func1()
{
  Form1.Textbox1.Text = "";
  Form1.Textbox2.Text = "";
}



Now I need to modify Func1 so that it clears either Form1 or Form2 depending on a variable passed to it. Unfortunately I cannot find an easy way to do this without making the code quite long.

In this example, it would be quite easy to simply include an if statement and pass a boolean variable saying which form it was called from, but the actual code is far longer than this. Unfortunately, I am developing it for internal use at a company and so cannot divulge many details about it. Because it is for internal use, is not likely to be developed very much, and will only be used by myself and a small handful of other people, I am not worried about good programming style.

I tried doing something along the lines of

public static void Func1(Form myForm, bool f1)
{
  Form main;

  if (f1)
  {
	main = (Form1) myForm;
  }
  else
  {
	main = (Form2) myForm;
  }

  main.Textbox1.Text = "";
  main.Textbox2.Text = "";
}



but this, of course, doesn't allow me access to the individual controls at run-time as the controls are not built into the Form class. Is there any way I can either change the type of a variable in one or two lines of code, or somehow make Func1 not care what type of Form is passed to it and allow access to its controls anyway? Obviously there can be some pretty big problems if it attempts to access a control that doesn't exist on one form or another, but I was told that this program only needed to work, it didn't necessarily have to be all that stable or error-proof.

In my actual program, there are indeed only two forms, but there are upwards of 40 controls, and not all of them are textboxes and so need special code to go with them. All the conditions for these controls are the same on both forms, but the forms are of different types, which is where my issue above comes in. To provide a little more detail that may make it easier to understand why these forms must be separate, one of the forms is used for writing a text file in a specific format, and the other is used for editing and deleting existing files of that format.

I have searched around on Google but cannot find a solution to this problem. Or rather, if I did find a solution, it was written in such a way that it was too confusing for me to understand.

Any help that can be provided is greatly appreciated.
Thanks,
~ Shaun

This post has been edited by Drakmyth: 28 July 2008 - 12:30 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Same control names on multiple forms

#2 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 29 July 2008 - 11:56 AM

Does no one know of any way to accomplish what I am trying to do? I am finding it quite difficult to continue developing this application without this issue being resolved.

~ Shaun
Was This Post Helpful? 0
  • +
  • -

#3 rgfirefly24  Icon User is offline

  • D.I.C Lover
  • member icon


Reputation: 260
  • View blog
  • Posts: 1,419
  • Joined: 07-April 08

Re: Same control names on multiple forms

Posted 29 July 2008 - 12:10 PM

Why don't you place the function indepentantly on each form. That way when the function is called it is called specific to the form its on. This way you only need to put in the nessisary details to clear the control instead of having to try and distinguish as to which form its on. If that doesnt work for you then just create a base class with a generic function that clears the controls. Since they are named the same then you dont have to worry about what form they are on, just know that when you call it from form 1 it clears form one and when you call it from form 2 it clears form 2.
The only thing you need to change on your forms is what is being inherited from.
Was This Post Helpful? 0
  • +
  • -

#4 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 29 July 2008 - 12:23 PM

What you mentioned about a generic function sounds exactly like what I need, but I have no idea how to code such a function. I will see what I can find about making generic functions, but in the mean time would it be possible for you to post an example of such a function?

Thank you very much,
~ Shaun

This post has been edited by Drakmyth: 29 July 2008 - 12:23 PM

Was This Post Helpful? 0
  • +
  • -

#5 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: Same control names on multiple forms

Posted 29 July 2008 - 01:29 PM

here is a little form and class i just wrote to show you a generic function first the form
public partial class Form1 : Form
    {
        Class1 class1 = new Class1();
        public Form1()
        {
            InitializeComponent();
        }
        // clear button on form1
        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = class1.Func1(this.textBox1.Text);
            this.textBox2.Text = class1.Func1(this.textBox2.Text);
        }
    }



now the class
    public class Class1
    {
        private static Class1 instance = null;

        public static Class1 Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Class1();
                }
                return instance;
            }
        }
        public Class1()
        {

        }
        // clears all string values.
        public string Func1(string val)
        {
            val = string.Empty;
            return val;
        }
    }


Was This Post Helpful? 0
  • +
  • -

#6 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 07:46 AM

Thanks for the example zakary, but I'm not sure I'm going to be able to use it. Before I worry about that though, perhaps you can clear up a bit about this example.

Based on this, am I right in understanding that a "generic function" doesn't necessarily have anything to do with "Generics"? I don't see how having Func1 take a string parameter, set it equal to string.Empty (which is better than = ""?), and returning that parameter is any different than having it take no parameters and just returning an empty string in the first place.

I certainly see how this works, and could be called from two different forms with the same result, but that's not quite what I'm looking for. The following would be a bit closer to what I am trying to do (note that the following code most certainly does not work)

First Form1, which contains a textBox1, a textBox2, and a button1.
public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
    textBox1.Text = "Hello";
    textBox2.Text = "World!";
    button1.Text = "Update Status";
  }

  private void button1_Click(object sender, EventArgs e)
  {
    Class1.UpdateStatus(this);
  }
}



Now Form2, also containing a textBox1, textBox2, and button1.
public partial class Form2 : Form
{
  public Form2()
  {
    InitializeComponent();
  }

  private void Form2_Load(object sender, EventArgs e)
  {
    textBox1.Text = "Hello 2";
    textBox2.Text = "World! 2";
    button1.Text = "Update Status 2";
  }

  private void button1_Click(object sender, EventArgs e)
  {
    Class1.UpdateStatus(this);
  }
}



and finally Class1
class Class1
{
  public static void UpdateStatus(Form f)
  {
    f.textBox1.Text = "TextBox1";
    f.textBox2.Text = "TextBox2";
    f.button1.Text = "Status Updated";
  }
}



The issue comes in with the static "UpdateStatus" function because it cannot find the textboxes and button. This makes sense seeing as those are individual controls and not part of the form itself, and so not all forms would have them. It is this that I am trying to do, except with far more controls of various types, and not necessarily simply changing the text on each of them.

I could just create a second copy of the function and use one or the other depending on the form, but in the interest of not having redundant functions, I wonder if there is a better way.

Thanks again,
~ Shaun
Was This Post Helpful? 0
  • +
  • -

#7 rgfirefly24  Icon User is offline

  • D.I.C Lover
  • member icon


Reputation: 260
  • View blog
  • Posts: 1,419
  • Joined: 07-April 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 08:31 AM

What your going to want to do is instead of using a function just place the code in the button1_Click.

for what you want to do there is actually no reason to have a function.
Was This Post Helpful? 0
  • +
  • -

#8 djkitt  Icon User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 189
  • Joined: 22-May 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 08:34 AM

Hey there Shaun,

Are you looking for something like the following?
using System;
using System.Windows.Forms;

namespace testStuff
{
    class Utils
    {


        // Clear all Controls In a Container that have a Text property 
        public static void ClearContainer(Control Container, bool ClearSubContainers)
        {
            foreach (Control c in Container.Controls)
            {
                if (c.GetType() == typeof(Label)  || c.GetType() == typeof(Button))
                {
                    //Skip Labels and Buttons - We don't want to clear these.
                }
                // Do not clear the text field of a groupbox
                else if (c.Controls.Count > 0)
                {
                    // Clear the fields in panels, groupboxes etc... (if ClearSubContainers == true)
                    if (ClearSubContainers) ClearContainer(c, ClearSubContainers);
                }
                else if (c.GetType().GetProperty("Text") != null)
                {
                    System.Reflection.PropertyInfo info = c.GetType().GetProperty("Text");
                    info.SetValue(c, "", null);
                }
            }
        }

    }
}


//USAGE:

            Utils.ClearContainer(this, true); // this would clear the current form
            Utils.ClearContainer(Form1, true); // this would clear the Form instance 'Form1'
            Utils.ClearContainer(Panel1, true); // this would clear the Panel 'Panel1'          



*EDITED: I added Buttons to the skip area - I use this to reset panels, but it works for forms too (So I forgot to block buttons)

I am just clearing a form here, but you could check for control name/type and do something else...

PsychoCoder has a snippet that is similar, but resets more types at http://www.dreaminco...snippet1238.htm


Hope this helps,

This post has been edited by djkitt: 30 July 2008 - 09:21 AM

Was This Post Helpful? 1
  • +
  • -

#9 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 09:13 AM

@ rgfirefly24:
If this were a simple program changing the text of 3 controls, yes, I would just place it in the button1 click event. But my program has upwards of 40 controls including textboxes, checkboxes, listboxes, and combo boxes. Also, I'm not actually clearing these individual fields, but rather filling them in with values from a text file.

I already have this working with one form, but I would like to simply extend this method so that it can use a form passed to it of any type. It is entirely possible that the form passed may not have these controls on it, but if possible I want the compiler to ignore that fact as I can guarentee the forms do indeed have these controls on it, regardless of what type they are.


---

@ djkitt
It looks like that snippet you posed is actually pretty close to what I'm looking for. As I am a VB6 programmer who just recently moved over to .NET, I'm not used to thinking of Forms as anything but Forms, when now they are actually Controls. I'll see if I can adapt what you've got there to fit. The only thing I worry about is that there are actually more controls on Form1 that are not on Form2. These additional controls do not get filled in my by function while your snippet looks like it just loops through all the controls on a form. I'm not sure how I would distinguish the additional controls from Form1 out of it. But if I'm reading it right, it certainly looks like it might help. Thanks.

---

~ Shaun
Was This Post Helpful? 0
  • +
  • -

#10 djkitt  Icon User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 189
  • Joined: 22-May 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 09:29 AM

View PostDrakmyth, on 30 Jul, 2008 - 11:13 AM, said:

@ djkitt
It looks like that snippet you posed is actually pretty close to what I'm looking for. As I am a VB6 programmer who just recently moved over to .NET, I'm not used to thinking of Forms as anything but Forms, when now they are actually Controls. I'll see if I can adapt what you've got there to fit. The only thing I worry about is that there are actually more controls on Form1 that are not on Form2. These additional controls do not get filled in my by function while your snippet looks like it just loops through all the controls on a form. I'm not sure how I would distinguish the additional controls from Form1 out of it. But if I'm reading it right, it certainly looks like it might help. Thanks.

---

~ Shaun


If you can put the extra controls on a separate panel you can check for the name of that panel and skip it - or you could put "Clear" in the Tag field of controls you want to clear and check for that or lots of other things. If you are modifying controls based on their names then just set up a switch/case on c.Name...

		// Clear all Specified Controls In a Container
		public static void ClearContainer(Control Container, bool ClearSubContainers)
		{
			foreach (Control c in Container.Controls)
			{
				switch (c.Name)
				{
					case "txtOne":
						c.Text = "1";
						break;
					case "txtTwo":
						c.Text = "2";
						break;
				}

				if (ClearSubContainers) ClearContainer(c, ClearSubContainers);

			}
		}


Was This Post Helpful? 0
  • +
  • -

#11 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: Same control names on multiple forms

Posted 30 July 2008 - 09:53 AM

here is the problem with what you are trying to do. The Class has no idea what the Form contains, so to say form.Textbox1.text is invalid with in that class. Now if every control is the same you can make a collection of that control and then uses delegates to handle your events.
Was This Post Helpful? 0
  • +
  • -

#12 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 10:46 AM

View Postzakary, on 30 Jul, 2008 - 09:53 AM, said:

here is the problem with what you are trying to do. The Class has no idea what the Form contains, so to say form.Textbox1.text is invalid with in that class. Now if every control is the same you can make a collection of that control and then uses delegates to handle your events.


That's precisely the issue. I know there is no way for the Class to know what's on the form. I was wondering if there was some really nasty trick to getting the class to not care, try anyway, and let whatever happens happen, because I as the programmer know that it will never be possible for the class to get a form that doesn't have the controls on it. If this program were going to be released to any more than the four or so people I'm making it for, I would certainly never consider trying such a thing. I'm kinda hoping against hope here since pretty much everything I know about coding says this isn't possible, but I've seen some nasty "features" crop up in languages before. ("yield" keyword anyone? :P)

The big thing here is that I'm trying to take the lazy way out. I was hoping I could add a few lines at the beginning, maybe a cast or two, and then make the whole thing magically work without having to rewrite the function. I've gotten pretty close, but it comes down to the fact that too much is done at compile time. I currently have Func1 taking 'Form m' as a variable, then in the function doing 'var myForm = (Form1)m;'. This works on form one, but 'Form2' cannot be cast to 'Form1' and so causes a runtime error when it tries. If there was a way to choose the type of the 'myForm' variable at runtime, then I could just set it to the actual type of 'm' and everything would be fine. I was hoping it could be done through Reflection, but I know very little about Reflection and finding good examples of how to use it is quite difficult.

Thanks for all the help guys, but it looks like I might have to stop being lazy and actually rewrite this function, or at least add a decent chunk of code to it.

Thanks,
~ Shaun

This post has been edited by Drakmyth: 30 July 2008 - 11:05 AM

Was This Post Helpful? 0
  • +
  • -

#13 djkitt  Icon User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 189
  • Joined: 22-May 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 11:36 AM

OK then,

How about this:

		public static void SetControls(Control container)
		{
			container.Controls["textBox1"].Text = "T1";
			container.Controls["textBox2"].Text = "T2";
		}



You can put it inside a try/catch block just in case...

This post has been edited by djkitt: 30 July 2008 - 11:38 AM

Was This Post Helpful? 0
  • +
  • -

#14 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 12:45 PM

oh wow, that does look like a nasty hack :D

I'll give that a try as soon as I can and let you know how it works.

Thanks again for all the help,
~ Shaun
Was This Post Helpful? 0
  • +
  • -

#15 Drakmyth  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 28-July 08

Re: Same control names on multiple forms

Posted 30 July 2008 - 01:01 PM

Normally I try not to double-post, especially if I don't need to bump, but I'm not sure if editing my previous post would re-mark this topic as 'new post'

I punched that in and it seems to have worked fine for most controls. But I've run into a bit of a snag with checkboxes (*.checked) and combo boxes (*.SelectedItem). Can't compile right now so I don't know if it's going to work, but it's not giving me compile errors on the rest of the lines. Does the "key" parameter for the Controls array default to the name of the control? It doesn't look like any of the controls have a "key" property.

~ Shaun
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2