Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on [email protected] for help. Thanks :)
Hello All, This is just a friendly reminder to read the Forum Charter where you wish to post before posting in it. :)

C# shopping basket, trying to remove an item...

2456789

Comments

  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    I think this is what you're referring to John...

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;
    using System.Collections.Specialized;
    using AjaxControlToolkit;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Web.SessionState;
    using System.Text;

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

    protected System.Web.UI.WebControls.LinkButton Delete_Btn;


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    I've noticed that when I add an item to my basket and get up the "Delete" LinkButton, when I hover the mouse over the LinkButton, I get the text in the image below at the bottom of the screen. I'm wondering why "Javascript" is coming up there??? I didn't think there was any JS going on here??? :confused::confused::confused:

    Just to clarify, the number 227 in the attached image is the dynamic ID of the LinkButton as set by the line of code below...

    Delete_Btn.ID = string.Format(DataReader["Project_id"].ToString());

    This just reads a unique ID from my DB...


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    I think this is what you're referring to John...

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;
    using System.Collections.Specialized;
    using AjaxControlToolkit;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Web.SessionState;
    using System.Text;

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

    protected System.Web.UI.WebControls.LinkButton Delete_Btn;

    No, I was referring to the piece of code that instantiates the delete button and adds it to the panel/placeholder.

    What you've pasted there simply declares the link button, which will be null until it's instantiated.


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    I've noticed that when I add an item to my basket and get up the "Delete" LinkButton, when I hover the mouse over the LinkButton, I get the text in the image below at the bottom of the screen. I'm wondering why "Javascript" is coming up there??? I didn't think there was any JS going on here??? :confused::confused::confused:

    Just to clarify, the number 227 in the attached image is the dynamic ID of the LinkButton as set by the line of code below...

    Delete_Btn.ID = string.Format(DataReader["Project_id"].ToString());

    This just reads a unique ID from my DB...

    When you attach an event handler to an ASP.net control it automatically renders the control with javascript (or at least a Microsoft version of JS) to do a postback.


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    You need to add the Buttons in the page lifecycle in the Init phase..

    Added controls do not survive postback as well so you need to them to the viewstate/database to make them work correctly otherwise what happens is you cannot keep an eye on them...

    Dynamically added controls can a pain to work, i just finished a project based around a whole load of them (custom user controls that you could keep adding etc to the page) and its a nightmare to get right..

    Anyways event handlers for any of the objects should be added on the Init phase.
    protected override void OnInit(EventArgs e)
            {
               //add event handlers here
    }
    

    And in the case of dynamically added objects when they are created

    You can also add a RepeaterEventHandler for your link buttom

    eg

    private void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e), if you are using a custom user control (ascx) file which raises a command to the repeater


  • Advertisement
  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    I knew I should have bought the ecommerce uncle bens boil in the bag product! :D:D:D

    I've been away from my PC since the weekend so I haven't had a chance to try this out but thanks so much to John & Ginger for the help with this... I'll get a chance tomorrow to rummage through my code and try to knock this one on the head.


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    I knew I should have bought the ecommerce uncle bens boil in the bag product! :D:D:D

    I've been away from my PC since the weekend so I haven't had a chance to try this out but thanks so much to John & Ginger for the help with this... I'll get a chance tomorrow to rummage through my code and try to knock this one on the head.

    No problem Darragh :)

    Stick with it because once you grasp it you'll know it forever, and will have no problems creating and using your own user controls which will allow for easier reusability.


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Ok, I'm going to revisit this today and see if I can get her over the fence!


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Here's my main issue now... I can get the delete item function to work when I put the code for it into the Page_Load function. Now that's grand but I have it where it is, (currently in the Button1_Click function because I want it to work when an item is added to the shopping basket/cart), so that it works when the button is clicked. If I move the code to somewhere else, it simply won't work because the instance of my Linkbutton will not be created for each item that is added to my shopping basket (this happens when the Button1_Click event is triggered which works fine at the moment). I'm getting this stupid:

    CS0122: 'System.Web.UI.WebControls.LinkButton.OnClick(System.EventArgs)' is inaccessible due to its protection level

    error even though all my functions are now public after being changed from protected to public. :mad: :confused::(


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    Here's my main issue now... I can get the delete item function to work when I put the code for it into the Page_Load function. Now that's grand but I have it where it is, (currently in the Button1_Click function because I want it to work when an item is added to the shopping basket/cart), so that it works when the button is clicked. If I move the code to somewhere else, it simply won't work because the instance of my Linkbutton will not be created for each item that is added to my shopping basket (this happens when the Button1_Click event is triggered which works fine at the moment). I'm getting this stupid:

    CS0122: 'System.Web.UI.WebControls.LinkButton.OnClick(System.EventArgs)' is inaccessible due to its protection level

    error even though all my functions are now public after being changed from protected to public. :mad: :confused::(

    I don't quite follow you there. Can you provide some code?


  • Advertisement
  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    John_Mc wrote: »
    I don't quite follow you there. Can you provide some code?

    Here's the complete code John, from the questions I've asked so far, it seems I have to recreate the control on postback. I've tried moving my Linkbutton code out of where it is below and up into the Page_Load function and when I do this, it will work/fire as a Linkbotton, but it won't work properly in the context of the wider project, which I need to create a link button for every item in my shopping cart using the while loop below...

    The error I'm getting now on the basis of the code below is:

    'System.Web.UI.WebControls.LinkButton.OnClick(System.EventArgs)' is inaccessible due to its protection level I changed all the "protected" settings to "public" to see if that sorted it but no luck so I changed them all back to "protected"...


    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;
    using System.Collections.Specialized;
    using AjaxControlToolkit;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.Web.SessionState;
    using System.Text;

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


    public void Page_Load(object sender, EventArgs e)
    {
    if (this.Session["dummy"] == null) { this.Session["dummy"] = 1; } lblSessionID.Text = this.Session.SessionID;

    }


    protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
    {
    // Get selected values
    string make = DropDownList1.SelectedItem.Text;
    string model = DropDownList2.SelectedItem.Text;
    string color = DropDownList3.SelectedItem.Text;

    // Output result string based on which values are specified
    if (string.IsNullOrEmpty(make))
    {
    Label1.Text = "Please Select an Engine Type.";
    }
    else if (string.IsNullOrEmpty(model))
    {
    Label1.Text = "Please select a model.";
    }
    else if (string.IsNullOrEmpty(color))
    {
    Label1.Text = "Please Select a Make.";
    }
    else
    {
    string dropdowna = DropDownList1.SelectedValue;
    string dropdownb = DropDownList2.SelectedValue;
    string dropdownc = DropDownList3.SelectedValue;


    DateTime myDateTime1 = new DateTime();
    myDateTime1 = new DateTime();
    myDateTime1 = DateTime.Now;

    string selectSQL;

    //Connection for SELECT FROM "Vehicle data"
    SqlConnection connz = new SqlConnection("Data Source=My Working Connection String");
    connz.Open();

    selectSQL = "SELECT * FROM Vehicle_Data WHERE Vehicle_Make = '" + DropDownList1.SelectedItem.Value + "' AND Vehicle_Model = '" + DropDownList2.SelectedItem.Value + "' AND Engine_Type = '" + DropDownList3.SelectedItem.Value + "'";

    SqlCommand cmdy = new SqlCommand(selectSQL, connz);
    cmdy.CommandType = CommandType.Text;

    SqlDataReader myDataReader;
    myDataReader = cmdy.ExecuteReader();

    Label1.Text = string.Format("Vehicle Information: {0} {1}.", make, model);
    Label7.Text = string.Format("Engine Type: {0}.", color);

    while (myDataReader.Read())
    {
    Label2.Text = string.Format("Your Purchase ID is: {0} ", myDataReader["Stock_Code"]);
    Label12.Text = string.Format("Retail Price: €");
    Label14.Text = string.Format("Product Info: ");
    Label3.Text = string.Format("{0:F2}", myDataReader["Retail_Price"]);
    Label4.Text = string.Format("{0} ", myDataReader["Product_Description"]);
    Label5.Text = string.Format("{0} ", myDataReader["Component_Manufacturer"]);
    Label15.Text = string.Format("Manufacturer: ");
    Label6.Text = string.Format("Timestamp: {0} ", myDateTime1);

    }

    myDataReader.Close();
    connz.Close();
    }
    }

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
    {
    return new CarsService().GetDropDownContents(knownCategoryValues, category);
    }

    public void Button1_Click(object sender, EventArgs e)
    {
    SqlConnection conn = new SqlConnection("Data Source=My Working Connection String");
    conn.Open();

    string TransDateTime = DateTime.UtcNow.ToString("r");
    string Delivery = string.Format("7.50");
    string dropdown1 = DropDownList1.SelectedValue;
    string dropdown2 = DropDownList2.SelectedValue;
    string dropdown3 = DropDownList3.SelectedValue;
    string Manufacturer = Label5.Text;
    string Description = Label4.Text;
    string Retail = Label3.Text;
    string SessionID = lblSessionID.Text;

    string sql = "insert into used_equipment (eq_type, eq_make, eq_model, SessionID, Retail_Price, Component_Manufacturer, Product_Description, Date_Time, Delivery_Cost)\n";
    sql += "values(";

    sql += "'" + dropdown1 + "',";
    sql += "'" + dropdown2 + "',";
    sql += "'" + dropdown3 + "',";
    sql += "'" + SessionID + "',";
    sql += "'" + Retail + "',";
    sql += "'" + Manufacturer + "',";
    sql += "'" + Description + "',";
    sql += "'" + TransDateTime + "',";
    sql += "'" + Delivery + "')";

    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    conn.Close();



    string selectSQLX;
    string selectSUM;
    string SumDelivery;

    SqlConnection connT = new SqlConnection("Data Source=My Working Connection String");
    connT.Open();

    SqlConnection connP = new SqlConnection("Data Source=My Working Connection String");
    connP.Open();

    SqlConnection connX = new SqlConnection("Data Source=My Working Connection String");
    connX.Open();

    selectSQLX = "SELECT * FROM used_equipment WHERE SessionID = '" + this.Session.SessionID + "'";
    selectSUM = "SELECT SUM(Retail_Price) FROM used_equipment WHERE SessionID = '" + this.Session.SessionID + "'";
    SumDelivery = "SELECT SUM(Delivery_Cost) FROM used_equipment WHERE SessionID = '" + this.Session.SessionID + "'";

    SqlCommand cmdy = new SqlCommand(selectSQLX, connT);
    cmdy.CommandType = CommandType.Text;

    SqlCommand cmdu = new SqlCommand(selectSUM, connP);

    SqlCommand cmdL = new SqlCommand(SumDelivery, connX);


    SqlDataReader DataReader;
    DataReader = cmdy.ExecuteReader();

    if (DataReader.HasRows)
    {
    //Label13.Text = "";

    while (DataReader.Read())
    {
    object obj1 = new object();
    obj1 = string.Format(DataReader["eq_type"].ToString());

    object obj2 = new object();
    obj2 = string.Format(DataReader["eq_make"].ToString());

    object obj3 = new object();
    obj3 = string.Format(DataReader["eq_model"].ToString());

    object obj4 = new object();
    obj4 = string.Format(DataReader["Component_Manufacturer"].ToString());

    object obj5 = new object();
    obj5 = string.Format(DataReader["Product_Description"].ToString());

    object obj6 = new object();
    obj6 = string.Format(DataReader["Retail_Price"].ToString());

    object obj7 = new object();
    obj7 = string.Format(DataReader["Project_id"].ToString());

    string newstring = string.Concat(obj1, " " + obj2, " " + obj3, "<br>" + obj4, " " + obj5, "<br>Retail Price: € " + obj6, "<BR>");

    Label Product_Label = new Label();
    Product_Label.ID = string.Format(DataReader["Project_id"].ToString());
    Product_Label.Text = newstring.ToString();

    LinkButton Delete_Btn = new LinkButton();
    Delete_Btn.ID = string.Format(DataReader["Project_ID"].ToString());
    Delete_Btn.Text = "Remove Item<BR><BR>";
    Delete_Btn.CommandName = "DeleteMe";
    Delete_Btn.PostBackUrl = "~/MainTestX.aspx";
    Delete_Btn.OnClick += new EventHandler(Delete_Btn_Click);
    Delete_Btn.CommandArgument = string.Format(DataReader["Project_id"].ToString());


    Panel1.Controls.Add(Product_Label);
    Panel1.Controls.Add(Delete_Btn);

    }

    decimal Cart = Convert.ToDecimal(cmdu.ExecuteScalar());
    decimal Carry = Convert.ToDecimal(Delivery);
    decimal Cart_Total = Cart + Carry;

    Label Shopping_Cart = new Label();
    Shopping_Cart.ID = "Cart";
    Shopping_Cart.Text = string.Format("Order Total: € {0} ", (Cart));

    Label Shipping_Label = new Label();
    Shipping_Label.ID = "Shipping";
    Shipping_Label.Text = string.Format("<BR>Shipping: € {0} ", (Carry));

    Label Order_Total = new Label();
    Order_Total.ID = "Order_Tot";
    Order_Total.Text = string.Format("<BR>Invoice Total: € {0} ", (Cart_Total));

    Panel1.Controls.Add(Shopping_Cart);
    Panel1.Controls.Add(Shipping_Label);
    Panel1.Controls.Add(Order_Total);



    }

    DataReader.Close();
    connT.Close();
    connP.Close();



    ////////////////////////////////////////////////////////////



    //End of test code block////
    }


    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void Button2_Click(object sender, EventArgs e)
    {

    }

    protected void Delete_Btn_Click(object sender, EventArgs e)
    {
    Response.Write("Hello World!");
    }

    }


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    The buttons need to be created in the Page_Load event, there's no way around that. If you create them in there then you wont need to also create them in the Button Click event handler.

    What's the "the context of the wider project" that prevents you from doing this?


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    If it was me, I would be doing this a slightly different way and throwing the whole thing in a repeater and you could then add a repeater command event to handle what happened with each link..

    This would then process all your information easier and give you some control


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    John_Mc wrote: »
    The buttons need to be created in the Page_Load event, there's no way around that. If you create them in there then you wont need to also create them in the Button Click event handler.

    What's the "the context of the wider project" that prevents you from doing this?

    I hope I can explain this right... As I see it, (going back to my very limited knowledge of C from long ago!), to create several instances of this Linkbutton, as I am doing (even though it doesn't "work" yet!), but to get one instance of the button created for each item in my shopping cart, I have to use a while loop as I have done to step through each item in the cart and at the same time create a Linkbutton to delete an item if required. Is there a way I can "Create" or "declare" the Linkbutton in the Page_Load function but actually "call" it in my while loop where I need it to be, in another function??? :confused::confused::confused:


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Ginger wrote: »
    If it was me, I would be doing this a slightly different way and throwing the whole thing in a repeater and you could then add a repeater command event to handle what happened with each link..

    This would then process all your information easier and give you some control

    I think I might try this Ginger, I'm not making much headway on this one as I'm trying to solve it at the moment. I've read up on a tutorial that deals with this very problem that I'm having but it sounds a bit hairy to be honest!

    http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_.aspx


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    Used that blog post to help with my understading of it

    I have made something similar and used a repeater with generic methods to handle the different number of controls I needed. All sitting in an AJAX tab control...

    the main premise is this

    You have a repeater which is bound to a list of items

    When you want to add a new item you a copy of the current list which is just a query on the repeater (ie get the number of items in the repeater)

    You copy that list and add your value and then bind your repeater to the list you just added to

    So that way all items are kept in viewstate without needing to ever worry because to get the list of items you just query the current repeater

    The idea for the delete is similar

    Delete works by you adding a command and there is a repeater item event to handle this event..

    You delete by index value so you get that from e.ItemIndex allowing you to delete the correct one

    For example

    you could have a number of textboxes to show and have their data stored in a List<string>

    So you have 10 textboxes with 10 values in your generic list

    You click the btn to add a new text box

    You get the current list of text boxes by getting all the text boxes in your repeater and copying the .Text property into the List<string>

    You take that list and add a new empty string to it

    You rebind your repeater to the List<string> from the above step

    You now have 11 textboxes 1 which is empty

    You decide to delete the one at position 2 (ie third one)

    You get teh current list again

    you get the ItemIndex of the link that raised the event and do a List.DeleteAt(e.ItemIndex) to remove the value

    You rebind and you have 10 boxes again

    The values of the text boxes are stored in the list not the text box itself if you get me

    Now say you want something more complex..

    Well you create the object with the different properties and then put that in a list instead...

    You can then have a user control that represents your object and have it bind to your object (not the list)


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Jesus that sounds seriously scary! I think I'm going to go back to PHP, I've run out of patience with the endless complications with ASP.NET. I think unless you have a seriously strong programming background, (which I don't have!), the lesson I've learnt is best avoid C# and asp.net!


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    Ok calm down

    Tis not complex, its quite simple to get..

    the idea is you get a list of items, add a value and give the list back to the thingy to work on.. sorta like any list you would use

    Right some sample code

    First the repeater which holds a placeholder for all the controls to be placed in it.

    I have a usercontrol called FExpertControl that I use to show the data from an FExpert object.
    
    <asp:Repeater ID="rptExpert" runat="server">
                            <ItemTemplate>
                                <asp:PlaceHolder ID="phExpert" runat="server"></asp:PlaceHolder>    
                            </ItemTemplate>
                        </asp:Repeater>
    
    

    I have in the code behind a List<FExpert> that handles the objects.

    in the OnInit part of the page life i add 2 event handlers to the repeater
    rptExpert.ItemCreated += RptExpertItemCreated;
                rptExpert.ItemCommand += RptExpertItemCommand;
    
    

    The ItemCreated is for add, the ItemCommand is for delete (or other things)

    The event handlers
    
     private void RptExpertItemCommand(object source, RepeaterCommandEventArgs e)
            {
                RemoveItem(rptExpert, CurrentExpertData, e);
            }
    
            private void RptExpertItemCreated(object sender, RepeaterItemEventArgs e)
            {
                AddControl<Expert>("~/Custom_Controls/FEControl.ascx", "phExpert", e);
            }
    
    

    Also I have a method to add the values to the list
    protected void AddExpert(object sender, EventArgs e)
            {
                AddItem(CurrentExpertData, rptExpert);
            }
    

    Now I have 2 generic methods that take care of what I need to do (I have about 10 different ASCX files for different objects on this page)

    They just take which repeater and what controls I want to use and do the neccessary to them

    Now you will see that this seems complex, but its not, you are just using a repeater like a database


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Ginger wrote: »
    Ok calm down

    Tis not complex, its quite simple to get..

    the idea is you get a list of items, add a value and give the list back to the thingy to work on.. sorta like any list you would use

    Right some sample code

    First the repeater which holds a placeholder for all the controls to be placed in it.

    I have a usercontrol called FExpertControl that I use to show the data from an FExpert object.
    
    <asp:Repeater ID="rptExpert" runat="server">
                            <ItemTemplate>
                                <asp:PlaceHolder ID="phExpert" runat="server"></asp:PlaceHolder>    
                            </ItemTemplate>
                        </asp:Repeater>
    
    

    I have in the code behind a List<FExpert> that handles the objects.

    in the OnInit part of the page life i add 2 event handlers to the repeater
    rptExpert.ItemCreated += RptExpertItemCreated;
                rptExpert.ItemCommand += RptExpertItemCommand;
    
    

    The ItemCreated is for add, the ItemCommand is for delete (or other things)

    The event handlers
    
     private void RptExpertItemCommand(object source, RepeaterCommandEventArgs e)
            {
                RemoveItem(rptExpert, CurrentExpertData, e);
            }
    
            private void RptExpertItemCreated(object sender, RepeaterItemEventArgs e)
            {
                AddControl<Expert>("~/Custom_Controls/FEControl.ascx", "phExpert", e);
            }
    
    

    Also I have a method to add the values to the list
    protected void AddExpert(object sender, EventArgs e)
            {
                AddItem(CurrentExpertData, rptExpert);
            }
    

    Now I have 2 generic methods that take care of what I need to do (I have about 10 different ASCX files for different objects on this page)

    They just take which repeater and what controls I want to use and do the neccessary to them

    Now you will see that this seems complex, but its not, you are just using a repeater like a database

    On that blog I mentioned above for the Dynamic Controls, there was a lot of talk about something you've mentioned above, the ascx page... According to his blog, I just need to create the control for the Linkbutton I need in an ascx page (I think), and then it is added to the control tree or recreated programatically on postback... I'm just afraid that all I need, over and above what I've done to date, is one or two lines of code to get this over the fence... What I have works perfectly except for the last little bit! :confused::confused::confused:


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    Also the List on the page is this

    private List<Expert> CurrentExpertData
    {
    get { return GetItemList<Expert>(rptExpert, "phExpert"); }
    }

    GetItemList is a generic method to read the repeater and the placeholder and return the objects in a List


  • Advertisement
  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    Darragh29 wrote: »
    On that blog I mentioned above for the Dynamic Controls, there was a lot of talk about something you've mentioned above, the ascx page... According to his blog, I just need to create the control for the Linkbutton I need in an ascx page (I think), and then it is added to the control tree or recreated programatically on postback... I'm just afraid that all I need, over and above what I've done to date, is one or two lines of code to get this over the fence... What I have works perfectly except for the last little bit! :confused::confused::confused:

    ASCX files are UserControls..

    Similar to the way that you use a text box or datagrid they are just controls you can make yourself

    Using my code samples above

    My FEControl is just 2 textboxes in a table organised in 2 rows

    In your case you can think of it as this.. what do I need to show in a single row and design it as such.

    Create an ASCX file by just adding a new user control to your project.

    Design the HTML/ Server controls the exact same was as an ASPX page (just leave out html/body tags)

    In your code behind, add a method like such
    private Expert _data;
    
     public override void DataBind()
            {
                if (Data != null)
                {
                     //assign textbox.text = Data.YourPropertyName
                    _data = null;
                }
    
                base.DataBind();
            }
    
    
      public Expert Data
            {
                get
                {
    
     if (_data == null)
                    {
                        _data = textBox.text //your stuff here
                    }
                    return _data;
                                }
                set { _data=value; }
            }
    

    My object Expert is a class which contains string properties, called name and number

    This will allow your control to be passed the object it expects and put all the values in the correct place...

    Now!

    You need one last thing, someway to say Delete ME!!!!!

    Add a linkbutton (you have them :D) and then add the following
    protected void RemoveItem(object sender, EventArgs args)
            {
                RaiseBubbleEvent(this, new CommandEventArgs("Remove", null));
            }
    
    

    My linkbutton onClick event is RemoveItem

    The RaiseBubbleEvent sends an event notice to the repeater which knows that when it recieves an event it uses the ItemCommand handler that you added before (see the previous post)

    You check to see is the event name called Remove and if it is, you can get the value of its index and remove it.


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    You see here's my problem, I've gotten to this point with a lot of help and some luck! I don't really fully understand how methods, functions, arguments and all that stuff works! It's taken me weeks of struggling and burning midnight oil just to get to where I have it at the moment, so if I've to go back and change the approach, I know I'll be into weeks of messing and trial by error because I don't really fully understand C# well enough or asp.net to just ditch one approach and pick up another one. I hope you see where I'm coming from with this, if I was a bit more fluent with it I'd probably give it a go but if I have to spend another 2 weeks at this the pc will be fired through the window and out onto the street!

    Do you think it would be possible can use an ascx user control to get over this headwrecker problem I'm having with my Linkbutton??? I'm so frustrated with it because it looks perfect, and must be close to working based on where I have it at the moment.

    If the Linkbutton has to be created in the Page_Load function, could I not just create the LinkButton there and call it somewhere else in my code???

    Or put my LinkButton code into the ascx file and call it up when I need it in my code???


  • Registered Users Posts: 2,931 ✭✭✭ Ginger
    Registered User


    I hear ya, I hear ya...

    The LinkButton is place in the ASCX file..

    Problem for you is this,

    By the time you assign your linkbutton handler in code it is too late in page cycle to work for it, hence why it worked in page load...

    You could put the whole thing in the page load and check if you are getting a command back so that it will work but its messy

    Something like

    If(Page.IsPostBack && Request.Form["fo"] == true)
    {
    Do whatever you did in the other function
    }


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    I've come up with a sort of a sh*ty solution but it's kind of getting me moving in the right direction again! Here goes...

    Just in relation to the LinkButton event, I've moved this into the Page_Load function but I've also created a new DB connection for the Linkbutton with a new while loop that kind of (but doesn't exactly yet!) replicates the behaviour of the LinkButton when it was in the Button1_Click function...

    So now my Page_Load which was empty except for the sessionID code, looks like this...

    public void Page_Load(object sender, EventArgs e)
    {
    if (this.Session["dummy"] == null) { this.Session["dummy"] = 1; } lblSessionID.Text = this.Session.SessionID;

    SqlConnection connUS = new SqlConnection("Data Source=My working connection string");
    connUS.Open();

    string selectSQLUS;

    selectSQLUS = "SELECT * FROM used_equipment WHERE SessionID = '" + this.Session.SessionID + "'";
    SqlCommand cmdUS = new SqlCommand(selectSQLUS, connUS);
    cmdUS.CommandType = CommandType.Text;

    SqlDataReader DataReader;
    DataReader = cmdUS.ExecuteReader();

    if (DataReader.HasRows)
    {
    //Label13.Text = "";

    while (DataReader.Read())
    {

    LinkButton Delete_Btn = new LinkButton();
    Delete_Btn.ID = string.Format(DataReader["Project_ID"].ToString());
    Delete_Btn.Text = "Remove Item<BR><BR>";
    Delete_Btn.CommandName = "DeleteMe";
    Delete_Btn.PostBackUrl = "~/MainTestX.aspx";
    Delete_Btn.Click += new EventHandler(Delete_Btn_Click);
    Delete_Btn.CommandArgument = ("12");
    Panel1.Controls.Add(Delete_Btn);
    }
    }
    }


    It needs to be tidyed up a bit but it's a fraction closer to where I was up until now with it.


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    You see here's my problem, I've gotten to this point with a lot of help and some luck! I don't really fully understand how methods, functions, arguments and all that stuff works! It's taken me weeks of struggling and burning midnight oil just to get to where I have it at the moment, so if I've to go back and change the approach, I know I'll be into weeks of messing and trial by error because I don't really fully understand C# well enough or asp.net to just ditch one approach and pick up another one. I hope you see where I'm coming from with this, if I was a bit more fluent with it I'd probably give it a go but if I have to spend another 2 weeks at this the pc will be fired through the window and out onto the street!

    Do you think it would be possible can use an ascx user control to get over this headwrecker problem I'm having with my Linkbutton??? I'm so frustrated with it because it looks perfect, and must be close to working based on where I have it at the moment.

    If the Linkbutton has to be created in the Page_Load function, could I not just create the LinkButton there and call it somewhere else in my code???

    Or put my LinkButton code into the ascx file and call it up when I need it in my code???

    You'll have to overcome the Page Life cycle hurdle using both approaches because they work the same way I'm afraid :o

    I had been programming in my spare time for about a year until I needed to code some functionality that required dynamically created controls, you on the other hand, are jumping straight in!

    To work with dynamically created controls, you need to understand the different stages that a page must go through before it's rendered as a html document to the client browser. It's absolutely essential that you know when events are hooked up, when controls should be added, viewstate is loaded or saved etc etc.

    I'd advise you to stick with it a little longer. When you do grasp it everything will click for you, and you'll be able to enjoy the benefits of reusable controls. There's no shortage of information about the Life cycle on google, so take a break from this project and find a tutorial which guides you through demonstrating what it is and how it works. Its impossible for us to explain it to you on here without writing our own article on it ;)


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    I've come up with a sort of a sh*ty solution but it's kind of getting me moving in the right direction again! Here goes...

    Just in relation to the LinkButton event, I've moved this into the Page_Load function but I've also created a new DB connection for the Linkbutton with a new while loop that kind of (but doesn't exactly yet!) replicates the behaviour of the LinkButton when it was in the Button1_Click function...

    So now my Page_Load which was empty except for the sessionID code, looks like this...

    public void Page_Load(object sender, EventArgs e)
    {
    if (this.Session["dummy"] == null) { this.Session["dummy"] = 1; } lblSessionID.Text = this.Session.SessionID;

    SqlConnection connUS = new SqlConnection("Data Source=My working connection string");
    connUS.Open();

    string selectSQLUS;

    selectSQLUS = "SELECT * FROM used_equipment WHERE SessionID = '" + this.Session.SessionID + "'";
    SqlCommand cmdUS = new SqlCommand(selectSQLUS, connUS);
    cmdUS.CommandType = CommandType.Text;

    SqlDataReader DataReader;
    DataReader = cmdUS.ExecuteReader();

    if (DataReader.HasRows)
    {
    //Label13.Text = "";

    while (DataReader.Read())
    {

    LinkButton Delete_Btn = new LinkButton();
    Delete_Btn.ID = string.Format(DataReader["Project_ID"].ToString());
    Delete_Btn.Text = "Remove Item<BR><BR>";
    Delete_Btn.CommandName = "DeleteMe";
    Delete_Btn.PostBackUrl = "~/MainTestX.aspx";
    Delete_Btn.Click += new EventHandler(Delete_Btn_Click);
    Delete_Btn.CommandArgument = ("12");
    Panel1.Controls.Add(Delete_Btn);
    }
    }
    }


    It needs to be tidyed up a bit but it's a fraction closer to where I was up until now with it.

    That looks alright, is it working for you?

    Can you get Delete_Btn_Click to fire?


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    John_Mc wrote: »
    That looks alright, is it working for you?

    Can you get Delete_Btn_Click to fire?

    Hi John,

    It's firing now but the overall shopping cart isn't working as it should. It's basically out of sync with the actual contents of the cart (as per the items being posted into the DB after a Button1_Click event is triggered) but I think this is due to the fact that when I fire the Button1_Click event, the page doesn't actually re-load again so what is going on in the Page_Load event doesn't get executed. I'm a little hazy on what is happening at the moment but I'll try to break it down bit by bit and see if I can understand what is happening and when.


  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    Just wondering is there a way I can put a line of code into a function that forces the page to refresh or to run the Page_Load function again???


  • Registered Users Posts: 2,785 ✭✭✭ John_Mc
    Registered User


    Darragh29 wrote: »
    Just wondering is there a way I can put a line of code into a function that forces the page to refresh or to run the Page_Load function again???

    Put the code that loads the cart into a function and call it from Page_Load and whenever the content of the cart is modified.

    private void LoadCart()
    {

    }


  • Advertisement
  • Closed Accounts Posts: 7,097 ✭✭✭ Darragh29


    John_Mc wrote: »
    Put the code that loads the cart into a function and call it from Page_Load and whenever the content of the cart is modified.

    private void LoadCart()
    {

    }

    But how do I "call it"??? I know these are basic questions, thanks for being patient with me on this! The way I survived this in uni was just horse everything into one function and somehow I managed to get away with it, so I never had to worry about working with different functions or arguments or methods or anything like that!


Advertisement