0

Okay this is probably a shot in the dark as it would be very difficult to guess what is going on here. But I am running out of options here.

So I have this code behind for a page that a user is able to fill out the input fields that are on the page and then by clicking the submit button, the information is added to the database. This works 100%. However, I want to put this functionality in a user control so I can use it on a different page but have the same effect. However I can't get this to work.

So here is the working code

The btnSubmit_Click method adds the information to the database without a problem.

Now for the user user control code. This doesn't do anything. The only difference I did was that it uses an ASPImageButton, which I had originally just a regular ASPButton but that didn't make a different.

So as I said a shot in the dark. If anyone has any suggestions on what to try or a fix please let me know. I can provide more information if needed.

Working Code:

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

using SenProPOS.Data;
using SenProPOS.Web.Classes;

namespace SenProPOS.Web.Admin.Pages
{
public partial class InventoryMaintenance : BasePage
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindInventoryEntries();
        }
    }

    #region Properties

    protected int CurrentInventoryID
    {
        get { return ViewState["CurrentInventoryID"] == null ? -1 : Convert.ToInt32(ViewState["CurrentInventoryID"].ToString()); }
        set { ViewState["CurrentInventoryID"] = value; }
    }

    protected int CurrentInventoryMaintPage
    {
        get { return ViewState["CurrentInventoryMaintPage"] == null ? 1 : Convert.ToInt32(ViewState["CurrentInventoryMaintPage"].ToString()); }
        set { ViewState["CurrentInventoryMaintPage"] = value; }
    }

    protected int InventoryEntriesPerPage
    {
        get { return Convert.ToInt32(ViewState["InventoryEntriesPerPage"] as String ?? "25"); }
        set { ViewState["InventoryEntriesPerPage"] = value; }
    }


    #endregion

    #region Methods

    private void BindInventoryEntries()
    {
        try
        {

            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                var inventories = context.Inventory_Items.ToList();

                String search = tbInventorySearch.Text.Trim().ToLower();
                if (!String.IsNullOrEmpty(search))
                {
                    inventories = inventories.Where(x => x.Name.ToLower().Contains(search)
                        || x.Description.ToLower().Contains(search.ToLower())
                        || x.UPC == Convert.ToInt32(search)
                        || x.Quantity == Convert.ToInt32(search)
                        || (double)x.Price == Convert.ToDouble(search)
                        || (double)x.Cost == Convert.ToDouble(search))
                        .ToList();
                }

                lvInventories.DataSource = inventories;
                lvInventories.DataBind();

                if (String.IsNullOrEmpty(this.lvInventories.SortExpression))
                {
                    lvInventories.Sort("Name", SortDirection.Descending);
                }

                /**
                var departments = context.Departments.ToList();
                this.ddlDepartment.DataSource = departments;
                this.ddlDepartment.DataValueField = "ID";
                this.ddlDepartment.DataTextField = "Name";
                this.ddlDepartment.DataBind();

                var categories = context.Categories.ToList();
                this.ddlCategory.DataSource = categories;
                this.ddlCategory.DataValueField = "ID";
                this.ddlCategory.DataTextField = "Name";
                this.ddlCategory.DataBind();
                 * **/

            }
        }
        catch (Exception ex)
        {
            ;
        }
    }

    private void InventoryEntrySelected(int InventoryID)
    {
        CurrentInventoryID = InventoryID;

        this.tbName.Text = String.Empty;
        this.tbUPC.Text = String.Empty;
        this.tbDescription.Text = String.Empty;
        this.tbQuantity.Text = String.Empty;
        this.tbPricePerUnit.Text = String.Empty;
        this.tbCostPerUnit.Text = String.Empty;
        this.ddlDepartment.SelectedIndex = -1;
        this.ddlCategory.SelectedIndex = -1;

        if (CurrentInventoryID != -1)
        {
            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                var inventory = context.Inventory_Items.SingleOrDefault(x => x.ID == CurrentInventoryID);
                if (inventory != null)
                {
                    this.tbName.Text = inventory.Name;
                    this.tbUPC.Text = inventory.UPC.ToString();
                    this.tbDescription.Text = inventory.Description;
                    this.tbQuantity.Text = inventory.Quantity.ToString();
                    this.tbPricePerUnit.Text = inventory.Price.ToString();
                    this.tbCostPerUnit.Text = inventory.Cost.ToString();

                    /** needs fixing yet
                    var department = this.ddlDepartment.Items.FindByValue(inventory..ToString());
                    if (department != null)
                    {
                        department.Selected = true;
                    }

                    var category = this.ddlCategories.Items.FindByValue(inventory.Category.ToString());
                    if (position != null)
                    {
                        position.Selected = true;
                    }

                    var category = this.ddlSuppliers.Items.FindByValue(inventory.Category.ToString());
                    if (supplier != null)
                    {
                        supplier.Selected = true;
                    }

                    **/
                }
                else throw new ApplicationException("The specified item was not found.");
            }
        }
    }

    #endregion

    #region Event Handlers

    protected override void OnPreRenderComplete(EventArgs e)
    {
        base.OnPreRenderComplete(e);
        RegisterListViewButtonsForAsyncPostback(lvInventories, "btnInventoryEntryEdit", "btnInventoryEntryDelete");
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
        this.btnInventoryAdd.Click += new EventHandler(btnInventoryAdd_Click);
        this.lvInventories.ItemCommand += new EventHandler<ListViewCommandEventArgs>(lvInventory_ItemCommand);
        this.lvInventories.PagePropertiesChanging += new EventHandler<PagePropertiesChangingEventArgs>(lvInventory_PagePropertiesChanging);
        this.tbInventorySearch.TextChanged += new EventHandler(tbInventorySearch_TextChanged);
    }

    void tbInventorySearch_TextChanged(object sender, EventArgs e)
    {
        BindInventoryEntries();
    }

    void btnInventoryAdd_Click(object sender, EventArgs e)
    {
        InventoryEntrySelected(-1);
    }

    void lvInventory_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        BindInventoryEntries();
    }

    void lvInventory_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("edit-item"))
        {
            InventoryEntrySelected(Int32.Parse(e.CommandArgument.ToString()));
        }
        else if (e.CommandName.Equals("delete-item"))
        {
            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                var inv = context.Inventory_Items.SingleOrDefault(x => x.ID == Int32.Parse(e.CommandArgument.ToString()));
                if (inv != null)
                {
                    context.Inventory_Items.DeleteOnSubmit(inv);
                    context.SubmitChanges();
                    BindInventoryEntries();
                }
            }
        }
        else if (e.CommandName.Equals("Sort") || e.CommandName.Equals("Page")) { BindInventoryEntries(); }
    }

    void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) { return; }

        try
        {
            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                Inventory_Item inv = null;
                if (CurrentInventoryID > 0)
                {
                    inv = context.Inventory_Items.SingleOrDefault(x => x.ID == CurrentInventoryID);
                }
                else
                {
                    inv = new Inventory_Item();
                    context.Inventory_Items.InsertOnSubmit(inv);
                }

                if (inv != null)
                {
                    if (!String.IsNullOrEmpty(this.tbName.Text))
                    {
                        inv.Name = this.tbName.Text;
                    }
                    else throw new ApplicationException("Invalid Name");

                    if (!String.IsNullOrEmpty(this.tbUPC.Text))
                    {
                        inv.UPC = Convert.ToInt64(this.tbUPC.Text);
                    }
                    else throw new ApplicationException("Invalid UPC#");

                    if (!String.IsNullOrEmpty(this.tbDescription.Text))
                    {
                        inv.Description = this.tbDescription.Text;
                    }
                    else throw new ApplicationException("Invalid Description");

                    if (!String.IsNullOrEmpty(this.tbQuantity.Text))
                    {
                        inv.Quantity = Convert.ToInt32(this.tbQuantity.Text);
                    }
                    else throw new ApplicationException("Invalid Quantity");

                    if (!String.IsNullOrEmpty(this.tbPricePerUnit.Text))
                    {
                        inv.Price = Convert.ToDecimal(this.tbPricePerUnit.Text);
                    }
                    else throw new ApplicationException("Invalid Price");

                    if (!String.IsNullOrEmpty(this.tbCostPerUnit.Text))
                    {
                        inv.Cost = Convert.ToDecimal(this.tbCostPerUnit.Text);
                    }
                    else throw new ApplicationException("Invalid Cost");

                    /**
                    int dep_id = 0;
                    if (Int32.TryParse(this.ddlDepartment.SelectedValue, out loc_id))
                    {
                        inv.Department = dep_id;
                    }
                    else throw new ApplicationException("Invalid Department");

                    int category = 0;
                    if (Int32.TryParse(this.ddlCategories.SelectedValue, out category))
                    {
                        inv.Category = category;
                    }
                    else throw new ApplicationException("Invalid Category");
                    **/
                    context.SubmitChanges();
                    BindInventoryEntries();
                }

            }
        }
        catch (ApplicationException ax)
        {
            ;
        }
    }

    #endregion

}
}

User Control Code:

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

using SenProPOS.Data;

namespace SenProPOS.Web.Controls
{
public partial class AddEditInventoryItem : System.Web.UI.UserControl
{
    public int? InventoryItemID = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindInventoryItemData();
            this.btnSubmit.Click += new ImageClickEventHandler(btnSubmit_Click);
        }
    }

    void btnSubmit_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                Inventory_Item inv = null;
                if (InventoryItemID > 0)
                {
                    inv = context.Inventory_Items.SingleOrDefault(x => x.ID == InventoryItemID);
                }
                else
                {
                    inv = new Inventory_Item();
                    context.Inventory_Items.InsertOnSubmit(inv);
                }

                if (inv != null)
                {
                    if (!String.IsNullOrEmpty(this.tbName.Text))
                    {
                        inv.Name = this.tbName.Text;
                    }
                    else throw new ApplicationException("Invalid Name");

                    if (!String.IsNullOrEmpty(this.tbUPC.Text))
                    {
                        inv.UPC = Convert.ToInt64(this.tbUPC.Text);
                    }
                    else throw new ApplicationException("Invalid UPC#");

                    if (!String.IsNullOrEmpty(this.tbDescription.Text))
                    {
                        inv.Description = this.tbDescription.Text;
                    }
                    else throw new ApplicationException("Invalid Description");

                    if (!String.IsNullOrEmpty(this.tbQuantity.Text))
                    {
                        inv.Quantity = Convert.ToInt32(this.tbQuantity.Text);
                    }
                    else throw new ApplicationException("Invalid Quantity");

                    if (!String.IsNullOrEmpty(this.tbPricePerUnit.Text))
                    {
                        inv.Price = Convert.ToDecimal(this.tbPricePerUnit.Text);
                    }
                    else throw new ApplicationException("Invalid Price");

                    if (!String.IsNullOrEmpty(this.tbCostPerUnit.Text))
                    {
                        inv.Cost = Convert.ToDecimal(this.tbCostPerUnit.Text);
                    }
                    else throw new ApplicationException("Invalid Cost");

                    /**
                    int dep_id = 0;
                    if (Int32.TryParse(this.ddlDepartment.SelectedValue, out loc_id))
                    {
                        inv.Department = dep_id;
                    }
                    else throw new ApplicationException("Invalid Department");

                    int category = 0;
                    if (Int32.TryParse(this.ddlCategories.SelectedValue, out category))
                    {
                        inv.Category = category;
                    }
                    else throw new ApplicationException("Invalid Category");
                    **/
                    context.SubmitChanges();
                    BindInventoryItemData();
                }

            }
        }
        catch (ApplicationException ax)
        {
            ;
        }
    }

    public void BindInventoryItemData()
    {
        this.tbName.Text = String.Empty;
        this.tbUPC.Text = String.Empty;
        this.tbDescription.Text = String.Empty;
        this.tbQuantity.Text = String.Empty;
        this.tbPricePerUnit.Text = String.Empty;
        this.tbCostPerUnit.Text = String.Empty;
        this.ddlDepartment.SelectedIndex = -1;
        this.ddlCategory.SelectedIndex = -1;

        if (InventoryItemID != -1)
        {
            using (SenProDataDataContext context = new SenProDataDataContext())
            {
                var inventory = context.Inventory_Items.SingleOrDefault(x => x.ID == InventoryItemID);
                if (inventory != null)
                {
                    this.tbName.Text = inventory.Name;
                    this.tbUPC.Text = inventory.UPC.ToString();
                    this.tbDescription.Text = inventory.Description;
                    this.tbQuantity.Text = inventory.Quantity.ToString();
                    this.tbPricePerUnit.Text = inventory.Price.ToString();
                    this.tbCostPerUnit.Text = inventory.Cost.ToString();

                    /** needs fixing yet
                    var department = this.ddlDepartment.Items.FindByValue(inventory..ToString());
                    if (department != null)
                    {
                        department.Selected = true;
                    }

                    var category = this.ddlSuppliers.Items.FindByValue(inventory.Category.ToString());
                    if (supplier != null)
                    {
                        supplier.Selected = true;
                    }

                    **/
                }
                else throw new ApplicationException("The specified item was not found.");
            }
        }
    }
}
}
7
  • 1
    Please, integrate the relevant parts of your code into your questions, not link it! We would like to have great questions on this site in complete form that never expires, and your links can expire one day or another! Commented Nov 23, 2011 at 6:29
  • @AlexanderGalkin Sorry, it is just a lot of code to indent so that it is readable. I will edit the question. Commented Nov 23, 2011 at 6:32
  • Yes, I visited your links and saw that your code is rather long, so I wrote "the relevant parts". :) I am not sure if one really needs all these "using" and the commented-out code to understand your question. Maybe you can skip even more? Commented Nov 23, 2011 at 6:42
  • Have you stepped through it in the debugger? Commented Nov 23, 2011 at 6:43
  • @Prescott Well I have been trying. I have been using the help pages on the VS website but the debugger says that the break point will not be hit because the symbol wasn't loaded with the document. I have no idea what that means so I can't figure out what I need to do to fix it. My best guess is that it doesn't think the user control is loaded? But it is as I can see it on the webpage. Commented Nov 23, 2011 at 6:51

3 Answers 3

1

Why don't you try putting ( this.btnSubmit.Click += new ImageClickEventHandler(btnSubmit_Click);) outside isnot postback?

Sign up to request clarification or add additional context in comments.

4 Comments

I just did this and the result was a compilation error: 'ASP.controls_addeditinventoryitem_ascx' does not contain a definition for 'btnSubmit_Click' and no extension method 'btnSubmit_Click' accepting a first argument of type 'ASP.controls_addeditinventoryitem_ascx' could be found (are you missing a using directive or an assembly reference?)
@yaegerbomb y dont u try putting ( this.btnSubmit.Click += new ImageClickEventHandler(btnSubmit_Click);) outside isnot postback
OMG i could kiss you right now. This solved it. I hope that is the end of the errors im getting. I cannot thank you enough.
if you put that as an answer I will mark it as right so you get credit for it.
0

Just a guess: Is the AspImageButton named "btnSubmit"? Is the Click event wired up correctly?

3 Comments

<asp:ImageButton ID="btnSubmit" Text="Submit" runat="server" ImageUrl="~/Style/Images/addButtonE.png"/> As far as I know it is wired correctly.
@yaegerbomb:where is the OnClick event for the image button?
@karthi I am not quite sure what you mean. I have the button linked by id and int he code behind (user control) this.btnSubmit.Click += new ImageClickEventHandler(btnSubmit_Click); handles the onclick? This is how I thought it was handled. I know I can put an onclick="" in the imagebutton but I am not sure what I would even put. In the working code I dont have an onclick in the .aspx file it is also <asp:Button ID="btnSubmit" Text="Submit" runat="server" /> and works fine.
0

When you add the control to your page you should use runat=”server” . I can give you an example

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <%@ register Src="~/WebUserControl.ascx" TagName="test" TagPrefix="testTag" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
     <testTag:test id="testId" runat="server" />   
</asp:Content>

Please look on,

<testTag:test id="testId" runat="server" />  

And be sure in your control u have used something like that

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/btn_submit.png" 
    onclick="ImageButton1_Click" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.