简体   繁体   中英

Access Dynamically User Control to aspx.cs file

I have created a dynamic control script in ASP.NET. Now as you see in the photo below...

在此处输入图片说明

Now what I want to do is the contents that are generated from UserDontrol, the values that are underlined I want to store them in database. I create a public class but in database it is stored as empty value (not NULL).

These are the codes:

.ascx.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class UserControl_ContactDetails : System.Web.UI.UserControl
{

    public String TextProperty
    {
        get
        {
            return LabelCmimi.Text;
        }
        set
        {
            LabelCmimi.Text = value;
        }
    }

    public void Page_Load(object sender, EventArgs e)
    {
        //if(Page.IsPostBack)
        //{
            DropDownListArtikulli.Text = Request.Form[DropDownListArtikulli.UniqueID];
            LabelCmimi.Text = Request.Form[LabelCmimi.UniqueID];
            TextBoxSasia.Text = Request.Form[TextBoxSasia.UniqueID];
            LabelVlera.Text = Request.Form[LabelVlera.UniqueID];
        //}

        Cmimi();
        Vlera();

        Session["Artikulli"] = DropDownListArtikulli.SelectedItem.ToString();
        Session["Cmimi"] = LabelCmimi.Text;
        Session["Sasia"] = TextBoxSasia.Text;
        Session["Vlera"] = LabelVlera.Text;
    }

    public void Cmimi()
    {
        DataTable listaArtikujt = new DataTable();

        using (SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
        {
            try
            {

                SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM [Artikujt]", lidhje);
                adapter.Fill(listaArtikujt);

                DropDownListArtikulli.DataSource = listaArtikujt;
                DropDownListArtikulli.DataTextField = "Artikulli";
                DropDownListArtikulli.DataValueField = "Cmimi";
                DropDownListArtikulli.DataBind();

               LabelCmimi.Text = DropDownListArtikulli.SelectedValue.ToString();

            }
            catch (Exception ex)
            {
                Response.Write("Gabim:" + ex.ToString());
            }
        }
    }

    public void Vlera()
    {
        if(!string.IsNullOrEmpty(TextBoxSasia.Text))
        {
            LabelVlera.Text = TextBoxSasia.Text.ToString();

            int a = Convert.ToInt32(LabelCmimi.Text);
            int b = Convert.ToInt32(LabelVlera.Text);

            int c = a * b;
            LabelVlera.Text = c.ToString();

            Session["Totali"] = (Session["Totali"] == null) ? 0 : Convert.ToInt32(Session["Totali"].ToString()) + c;     
        }
    }
}

.aspx.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class DynamicControl : System.Web.UI.Page
{
    private const string VIEWSTATEKEY = "ContactCount";

    protected void Page_Load(object sender, EventArgs e)
    {
        //Set the number of default controls
        ViewState[VIEWSTATEKEY] = ViewState[VIEWSTATEKEY] == null ? 1 : ViewState[VIEWSTATEKEY];

        Session["Totali"] = 0;

        //Load the contact control based on Vewstate key
        LoadContactControls();
    }

    private void LoadContactControls()
    {
        for (int i = 0; i < int.Parse(ViewState[VIEWSTATEKEY].ToString()); i++)
        {
            phContactDetails.Controls.Add(LoadControl("~/UserControl/ContactDetails.ascx"));
        }
    }

    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        ViewState[VIEWSTATEKEY] = int.Parse(ViewState[VIEWSTATEKEY].ToString()) + 1;
        LoadContactControls();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

    }

    protected void OK_Click(object sender, EventArgs e)
    {

        LabelTotal.Text = Session["Totali"].ToString(); 
    }
}

The question is... how can I store the values in database when I press the button "Dergo" (Button1_Click)?

PS A friend told me that the problem is cased by the user control have reload in my Page_Load event, so I get the value is always empty. And if I want to get the value, he suggested me to add a event in my user control, and then get my input value from the event. And e refer link http://msdn.microsoft.com/en-us/library/fb3w5b53(v=vs.100).aspx

I took his advice but I started learning ASP.NET 2 weeks ago and I didn't succeed. Can anyone help me with more info or write the code please? Thank You.

you need to define property on .ascx.cs to return value of the dropdwon , textbox , and controls you need their value... and in .aspx.cs and in click handler you can read usercontrol properties simply, like this USERCONTROL_ID.DropDownValue ... DropDownValue is a property on your user control like this:

public string DropDownValue
    {
        get
        {
            return DropDownList1.SelectedValue;
        }
    }

and then you can save everything you want in database

also you can have one property which return a object containing all values like:

public UserControlValue Value
    {
        get
        {
            return new UserControlValue(DropDownList1.SelectedValue, TextBox1.Text);
        }
    }
public class UserControlValue
{
    public UserControlValue(string property1, string property2)
    {
        this.property1 = property1;
        this.property2 = property2;
    }

    public string property1 {get; set;}
    public string property2 {get; set;}
}

and read this from aspx.cs like USERCONTROL_ID.Value.property1 or USERCONTROL_ID.Value.property2

how about get id of controls after loading and add them to session,

control o = LoadControl("~/UserControl/ContactDetails.ascx");
(Session["controlIDList"] as List<string>).Add(o.ID);

you need to create session before, maybe in page load using this

Session.Add("controlIDList", new List<string>());

and find controls from saved id list in session, and then cast to its type, and get the value you want...

(Session["controlIDList"] as List<string>).ForEach(u =>
{
    var c = (TYPE_OF_USERCONTROL)this.Page.FindControl(u);
    c.Value; // value is a property on user controls which return value of dropdown, textbox, and ....
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM