Skip to content

Editing an object and passing two parameters from that object to redirect to a page

October 22, 2012

Imagine using the Customer and Bank analogy, that you wanted to edit the customer’s bank account name but keep the same sort code in a GridView, you don’t want to delete the dictionary entry and add a new one, but edit an existing one.

Having used a HyperLinkColumn to do this, you can only use one paramter to be used as the DataTextField and DataNavigateUrlField, passing two won’t work as ASP.NET cannot parse two parameters into HyperLinkColumn.

The solution is to use a ButtonLinkColumn like so: –

            // Now add the HyperLink column to edit Customer
            ButtonColumn editLinkColumn = new ButtonColumn();
            editLinkColumn.CommandName = “edit”;
            editLinkColumn.DataTextField = “CustomerID”;
            editLinkColumn.DataTextFormatString = “edit”;
            editLinkColumn.Text = “edit”;
            editLinkColumn.ButtonType = ButtonColumnType.LinkButton;
            editLinkColumn.ItemStyle.Width = 30;

            tbl.Columns.Add(editLinkColumn);

And use the following method which gets invoke from the Edit Command: –

    protected void EditItem(object sender, DataGridCommandEventArgs e)
    {
        if (e.CommandName == “edit”)
        {
            DataGridItem container = (DataGridItem)e.Item;
            string customerName = container.Cells[1].Text;

            short sortCodeID = Convert.ToInt16(container.Cells[2].Text.ToString());

            Customer customer = Customer.GetCustomerrByName(customerName);

            if (customer != null)
            {
                Response.Redirect(“editcustomerbank.aspx?Customer=” + customer.CustomerID + “&SortCode=” + sortCodeID);
            }
            else
            {
                // Error, Customer cannot be removed
                pnlMessage.Visible = true;
                lblMessage.Text = “Customer Sort Code Bank cannot be found to be removed.”;
            }

        }
    }

Don’t forget to add the invoker methods to respond to: –

        tbl.ItemDataBound += new DataGridItemEventHandler(this.BindLinkButton);

        tbl.EditCommand += new DataGridCommandEventHandler(EditItem);

        tbl.DeleteCommand += new DataGridCommandEventHandler(DeleteItem);

(tbl is a DataGridTable, you just asssign DataGridTable tbl = new DataGridTable();)

There you go!

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: