Home > Back-end >  Initiating controls on webforms in FormView at class level
Initiating controls on webforms in FormView at class level

Time:10-10

I am maintaining a c# webforms project. There are many methods that carry out various functions by getting values form TextBox Controls, DropDownList Controls etc using FindControl as they reside on a FormView. Currently Controls are initialized in each Method, but the same Control may be initialized in say 7 Methods. Like so :-

    protected void GetGPPCM()
    {
        CheckBox Mortgage = (CheckBox)FormView1.FindControl("Mortgage");
        Literal Gross_Profit_PCM = (Literal)FormView1.FindControl("Gross_Profit_PCM");
        TextBox Rental_PCM = (TextBox)FormView1.FindControl("Rental_PCM");
        if (Mortgage.Checked)
        {
            TextBox Revrsionary_Rate_ABR = (TextBox)FormView1.FindControl("Revrsionary_Rate_ABR");
            decimal currentrate = GetRate()   System.Convert.ToDecimal(Revrsionary_Rate_ABR.Text.ToString());

            TextBox Capital_Amount = (TextBox)FormView1.FindControl("Capital_Amount");

            Gross_Profit_PCM.Text = "£"   String.Format("{0:n}", (Convert.ToDecimal(Rental_PCM.Text) - (((currentrate / 100) * Convert.ToDecimal(Capital_Amount.Text.ToString())) / 12)));
        }
        else
        {
            Gross_Profit_PCM.Text = "£"   String.Format("{0:n}", Convert.ToDecimal(Rental_PCM.Text));
        }
    }

What I want to do is declare all controls once only at class level, however when I move say :-

TextBox Rental_PCM = (TextBox)FormView1.FindControl("Rental_PCM");

directly under the class like

public partial class WebForm1 : System.Web.UI.Page
{

DropDownList ddlPropertyID = (DropDownList)FormView1.FindControl("ddlPropertyID");


}

I get a compile error Compiler Error CS0236 A field initializer cannot reference the non-static field, method, or property 'name'. Instance fields cannot be used to initialize other instance fields outside a method.

Is there any way I initialize all the controls I want, just once and not do it repeatedly in each method?

Thanks in advance.

CodePudding user response:

You have several approaches.

You can continue to say drop those controls on the current webform, and then say build helper routines. Those helper routines will load up the control, but not allow you to have event code outside of the current page. This can often work well.

If you looking to have event code for a given control, then create what is called a user control. They are not only brilliant but allow you to create controls (and more important event code) that can be used over and over.

So, don't try to create your own class - use the built-in choice that does all the work for you.

So, say I have a hotel drop down. Let's say we need this SAME combo box on many pages - used over and over.

So, create a user control, this choice:

enter image description here

This choice lets you:

Define the markup - place as many controls as you want into this "one thing".

And you now have event code, and now have your own re-useable control that you can use over and over.

So, let's make a hotel drop down.

You get a plain jane markup page - but it is ONLY markup.

It looks like this:

<h4>Select Hotel</h4>
<asp:DropDownList ID="cboHotels" runat="server" Width="150px"
    DataValueField="ID"
    DataTextField="HotelName" 
    OnSelectedIndexChanged="cboHotels_SelectedIndexChanged" 
    AutoPostBack="True"
</asp:DropDownList>

And that control has its "own" page load.

Also, any public member becomes part of the property sheet and settings for that control!!!

So, let's have a "extra" setting that we are to type in the target text box, and upon selecting we fill out that text box with the hotel name.

So, this code:

    private string _TargetBox = "";

    public string TargetBox
    {
        get { return _TargetBox; }
        set { _TargetBox = value; }

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // load up combo
            string strSQL = "SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                {
                    conn.Open();
                    cboHotels.DataSource = cmdSQL.ExecuteReader();
                    cboHotels.DataBind();
                    cboHotels.Items.Insert(0, new ListItem("Select", "0"));
                }
            }
        }
    }

    protected void cboHotels_SelectedIndexChanged(object sender, EventArgs e)
    {
        // user made selection

        if (TargetBox != "")
        {
            TextBox txtTarget = (TextBox)Page.FindControl(TargetBox);
            if (cboHotels.SelectedIndex == 0)
            {
                txtTarget.Text = "";
            }
            else
            {
                txtTarget.Text = cboHotels.SelectedItem.Text;
            }
        }
    }

That is it, we are done.

Now, we can start a brand new blank web page.

And we can then simple drag drop in this new re-usable control

Like this:

enter image description here

Our markup is now this, but NOTE how the property sheet has that optional Targetbox property.

So this:

enter image description here

When we run this page, we see this:

enter image description here

We also can add events to this control - they can and will run code behind on the current page.

so, don't try and roll your own system, the user control feature of web forms will do all this work for you.

Once that "user" control is created, then you have a drag drop control that you can drop into any page.

  • Related