GridView edit mode Edit/Delete link become button - how?

The standard Gridview edit mode provides "Edit" and "Delete" hyperlink (called linked button) for us to click and update record.

How to make them buttons instead of hyperlik ?

I could not find the codes for these 2 default hyperlinks to modify.

Thanks


Thanks in advance for the help. I will try to credit the ones who helped but most important is we really do sincerely thanks to all who have helped.
-1
hkbeer
7/12/2008 7:34:02 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
1307 Views

Similar Articles

[PageSpeed] 39
Get it on Google Play
Get it on Apple App Store

I found the solution. We can edit column and then change from link to button.

 


Thanks in advance for the help. I will try to credit the ones who helped but most important is we really do sincerely thanks to all who have helped.
0
hkbeer
7/12/2008 5:23:10 PM

Hi

try this example:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:label id="lblMessage" runat="server" enableviewstate="False" Font-Bold="True" />
	<asp:gridview id="gvShippers" runat="server" allowpaging="True" allowsorting="True"
		autogeneratecolumns="False" datakeynames="ShipperID" emptydatatext="There are no data records to display."
		onpageindexchanging="gvShippers_PageIndexChanging" onrowcancelingedit="gvShippers_RowCancelingEdit"
		onrowcommand="gvShippers_RowCommand" onrowdeleting="gvShippers_RowDeleting" onrowediting="gvShippers_RowEditing"
		onrowupdating="gvShippers_RowUpdating" onsorting="gvShippers_Sorting" showfooter="True"
		style="margin-top: 20px;" CellPadding="4" ForeColor="#333333" GridLines="None">
		<columns>
			<asp:templatefield>
				<itemtemplate>
					<asp:linkbutton id="btnSelect" runat="server" commandname="Select" text="Select" />
					<asp:linkbutton id="btnEdit" runat="server" commandname="Edit" text="Edit" />
					<asp:linkbutton id="btnDelete" runat="server" commandname="Delete" text="Delete" />
				</itemtemplate>
				<edititemtemplate>
					<asp:linkbutton id="btnUpdate" runat="server" commandname="Update" text="Update" />
					<asp:linkbutton id="btnCancel" runat="server" commandname="Cancel" text="Cancel" />
				</edititemtemplate>
				<footertemplate>
					<asp:linkbutton id="btnInsert" runat="server" commandname="Insert" text="Insert" />
				</footertemplate>
			</asp:templatefield>
			<asp:boundfield datafield="ShipperID" headertext="ShipperID" insertvisible="False"
				sortexpression="ShipperID" />
			<asp:templatefield headertext="CompanyName" sortexpression="CompanyName">
				<itemtemplate>
					<%# Eval("CompanyName") %>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtCompanyName" runat="server" text='<%# Eval("CompanyName") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtCompanyName" runat="server" />
				</footertemplate>
			</asp:templatefield>
			<asp:templatefield headertext="Phone" sortexpression="Phone">
				<itemtemplate>
					<%# Eval("Phone") %>
				</itemtemplate>
				<edititemtemplate>
					<asp:textbox id="txtPhone" runat="server" text='<%# Eval("Phone") %>' />
				</edititemtemplate>
				<footertemplate>
					<asp:textbox id="txtPhone" runat="server" />
				</footertemplate>
			</asp:templatefield>
		</columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#EFF3FB" />
        <EditRowStyle BackColor="#2461BF" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
	</asp:gridview>

    </div>
    </form>
</body>
</html>
and in code behind
 
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.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    private string Sort
    {
        get
        {
            return String.Concat(
                    this.SortExpression,
                    (this.SortDirection == SortDirection.Ascending) ? " ASC" : " DESC");
        }
    }

    private SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Ascending;
            }

            return (SortDirection)ViewState["SortDirection"];
        }
        set { ViewState["SortDirection"] = value; }
    }

    private string SortExpression
    {
        get
        {
            if (ViewState["SortExpression"] == null)
            {
                ViewState["SortExpression"] = "ShipperID";
            }

            return ViewState["SortExpression"].ToString();
        }
        set { ViewState["SortExpression"] = value; }
    }

    private void SetData()
    {
        SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("SELECT * FROM [Shippers]", conn);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);

        try
        {
            conn.Open();
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            DataView dv = dt.DefaultView;
            dv.Sort = this.Sort;

            gvShippers.DataSource = dv;
            gvShippers.DataBind();
        }
        finally
        {
            conn.Close();
        }
    }

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

    protected void gvShippers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShippers.PageIndex = e.NewPageIndex;

        this.SetData();
    }

    protected void gvShippers_Sorting(object sender, GridViewSortEventArgs e)
	{
        if (this.SortExpression.Equals(e.SortBLOCKED EXPRESSION)
        {
            this.SortDirection = (this.SortDirection == SortDirection.Ascending) ? SortDirection.Descending :SortDirection.Ascending;
        }
        else
        {
            this.SortDirection = SortDirection.Ascending;
        }

        this.SortExpression = e.SortExpression;

        this.SetData();
	}

    protected void gvShippers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvShippers.EditIndex = e.NewEditIndex;

        this.SetData();
    }

    protected void gvShippers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvShippers.EditIndex = -1;

        this.SetData();
    }

    protected void gvShippers_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow gvr = gvShippers.Rows[e.RowIndex];

        TextBox txtCompanyName = gvr.FindControl("txtCompanyName") as TextBox;
        TextBox txtPhone = gvr.FindControl("txtPhone") as TextBox;

        if (txtCompanyName == null) { return; }
        if (txtPhone == null) { return; }

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(
            "UPDATE [Shippers] SET [CompanyName] = @CompanyName, [Phone] = @Phone WHERE (ShipperID = @ShipperID)",
            conn);
        cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[gvr.RowIndex]["ShipperID"]);
        cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
        cmd.Parameters.AddWithValue("Phone", txtPhone.Text);

        try
        {
            conn.Open();

            if (cmd.ExecuteNonQuery().Equals(1))
            {
                lblMessage.Text = String.Format(
                    "Shipper '{0}' successfully updated.",
                    cmd.Parameters["ShipperID"].Value);

                gvShippers.EditIndex = -1;

                this.SetData();
            }
        }
        finally
        {
            conn.Close();
        }
    }

    protected void gvShippers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SqlConnection conn = new SqlConnection(
            ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(
            "DELETE FROM [Shippers] WHERE (ShipperID = @ShipperID)",
            conn);
        cmd.Parameters.AddWithValue("ShipperID", gvShippers.DataKeys[e.RowIndex]["ShipperID"]);

        try
        {
            conn.Open();

            if (cmd.ExecuteNonQuery().Equals(1))
            {
                lblMessage.Text = String.Format(
                    "Shipper '{0}' successfully deleted.",
                    cmd.Parameters["ShipperID"].Value);

                this.SetData();
            }
        }
        finally
        {
            conn.Close();
        }
    }

    protected void gvShippers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            LinkButton btnInsert = e.CommandSource as LinkButton;

            if (btnInsert == null) { return; }

            GridViewRow gvr = btnInsert.NamingContainer as GridViewRow;

            if (gvr == null) { return; }

            TextBox txtCompanyName = gvr.FindControl("txtCompanyName") as TextBox;
            TextBox txtPhone = gvr.FindControl("txtPhone") as TextBox;

            if (txtCompanyName == null) { return; }
            if (txtPhone == null) { return; }

            SqlConnection conn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand(
                "INSERT INTO [Shippers] ([CompanyName], [Phone]) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY()",
                conn);
            cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
            cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
            cmd.Parameters.Add("ShipperID", SqlDbType.Int);
            cmd.Parameters["ShipperID"].Direction = ParameterDirection.Output;

            try
            {
                conn.Open();

                if (cmd.ExecuteNonQuery().Equals(1))
                {
                    lblMessage.Text = String.Format(
                        "Shipper '{0}' successfully added.",
                        cmd.Parameters["ShipperID"].Value);

                    this.SetData();
                }
            }
            finally
            {
                conn.Close();
            }
        }
    }

}
 
Good Luck
1
yasserzaid
7/17/2008 8:36:30 PM
Reply:

Similar Artilces:

GridView control enters edit mode only when I click Edit link twice
Hi all..I have a GridView control in an ASP.NET 2.0 page. I added a column that contains edit, update, cancel buttons. Because I did that, I had to handle RowEditing event or an exception was thrown.Well... this is the body of the RowEditing event:protected void gvParametros_RowEditing(object sender, GridViewEditEventArgs e){      gvParametros.EditIndex = e.NewEditIndex;}The fact is that when page is loaded and I click the edit link, page is refreshed but GridView doesn't enter edit mode. When I press edit link again, GridView enters edit mode.Any help to solve this behavior w...

delete button in edit mode of a gridview
is there a way to add the delete functionality to the gridview while it is in edit mode? http://www.webswapp.com/codesamples/aspnet20/itemplate/gridview.aspxHTH,Phillip Williams,http://www.webswapp.com Yes switch you column for the edit/update/cancel to a template and add the following<asp:LinkButton id="DeleteButton" runat="server" CommandName="Delete" />And you will be all set.View My Blog Download My URL Rewriter and Reverse ProxyOnly $9.95/month, ASP.NET, 2GB & SQL 2005...

DataList with Nested Editable/Deletable Gridviews. Gridviews not updating parent on edit/delete.
<DataList "Groups">  <Item>      <DataBound Title in DataList>       <Gridview of Items in "Current Group from DataList">       <SqlDataSource for GridView> </Item></DataList><SqlDataSource for DataList> Everything displays fine, I can edit individual rows in the nested grids and I can insert Rows in the grids.But the edit/delete events will not trigger the DataList to rebind its contents.. so onEdit/onDelete in the gridviews I say "DataList.Dat...

using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value  from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: http://forums.asp.net/t/1069245.aspx Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help....

How to add the delete/edit buttons in GridView control ?
i have a GridView control that is bound dynamically to an AccessDataSource. the GridView control has the attribute 'AutoGenerateColumns' to be true. when i add a 'delete field' to the grid control (by code or by the edit columns feature), it gets added in the beginning of each row. however, i want it to be at the end of each row . how i can do it ? thanks  <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">                <Columns...

Direct editing of gridView or Ddatagrid controls without clicking on an EDIT link
I have an application where lots of data is presented to the user in a gridView control and the user needs the option to review and overwrite any values in the cells of the grid.  My users find it very annoying and time consuming to click on an edit link to turn a row of the gridView into edit mode.  Typically, they might jump around and edit a few values in several rows.  Is there any way to present the data in a gridView control, datagrid control or something that looks like a grid where the entire grid is already in edit mode?  Can you make a grid that cont...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

Gridview Edit go to new page and enter Edit mode on a formview control.
Okay, so far I have the edit button go to a page called update.aspx. And have the ID selected. However, I don't want it to be in selected view, I want it to go to the update.aspx page in edit mode not selected mode. Is this possible? You can add one hyperlink and set its path to update.aspx?Id=(selectedId)on update.aspx read Id's value from querystring and do updation - Hardik (Software Developer,Surat,India)Please remember to click "Mark as Answer" on this post if it helped you. You lost me at the "do updation part" so far I have a the EDIT link go to ...

GridView and Javascript
Hey All, I need help from  you. I have a GridView. In the  Edit Item template of the first Column I have a textbox, an user control and hidden field. When I click on the user control it  opens a pop up from which I can choose the required value. The text value is populated in the textbox and Id in the hidden field. Here's the code for edit template.         <EditItemTemplate>                        <table cellpaddin...

Confirmation message for delete link button conflict with edit's cancel link button
Hello, I have used the tutorial of ASP.net's confirmation message for the delete link button of the gridview, but it conflict with the edit's cancel link button. Would somebody teach me how to fix it? Thanks. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs  e)    {               if (e.Row.RowType == DataControlRowType.DataRow)        {             // reference the Delete LinkButton&...

Edit control is not loaded in edit mode
I have a problem that the dynamic data field edit control (such as TEXT_edit.ascx) is not loaded when in edit mode. Instead, the normal view control is loaded (such as Text.ascx). In debug I can determina the page mode is truly edit mode. Please help! Could you provide some more context: is this in a custom page with a custom column set or one of the default scaffold pages? Are you using a UIHintAttribute? Make sure the names of the display and edit versions match.Marcin DoboszSDE, ASP.NET Team, MicrosoftRead my blog This is just a thought are you using Views rather than ...

Edit Button is not switching to Edit Mode
Hello, i have this GridView. it's a very simple one. I add programmatically the datasource. The deal is that when i click on the Edit button (command button) it does not shows the edit controls. here is the code <asp:GridView ID="GridView1" runat="server" CssClass="Table2" AllowPaging="True"AllowSorting="True" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound" onrowdeleted="GridView1_RowDeleted"...

In a gridview, can I programatically control display of edit/delete buttons for selected row?
Hi there, I'm sure this is something fairly straight forward but I'm only just getting used to working with gridviews so please help me, I am displaying the select button on my gridview, and on the SelectedIndexChanged event I would like to add (or make visible) the edit and delete buttons just for the selected row - can I do this?  All help appreciated, JoH are you using template field with button / link button for edit or delete button  ?Thanx, [KaushaL] || BloG || Profile || Microsoft MVP"I would love to change the world, but they won’t give me ...

Handling control events while in edit mode for a gridview control
I have a dropdownlist and checkbox in a single column of a gridview. While the row is in edit mode, I want to set the visibility of the checkbox based on the value selected in the dropdown list. I can do this easily enough  when the row is first put into edit mode, but how do I access the dropdown list's change event when the row is already sitting there in edit mode? Thanks for any help you can provide.   Penny Penny, Just create a SelectedIndexChanged event like below. Create a row object for the currently edited row, find the checkbox you want to control, then set the Visib...

Web resources about - GridView edit mode Edit/Delete link become button - how? - asp.net.presentation-controls

GridView SelectedItem Binding Gotcha in WinRT
Last night when I was doing some WinRT hacking I was trying to setup databinding to the selected item in the GridView control and I ran into ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Advanced Search Gridview Latest News Releases All ...

CNW Group
... Services Beyond the Wire About CNW my CNW CNW Access CNW Directories Financials Webcasts Events my CNW All News Releases Advanced Search Gridview ...

CNW Group
Home Services Beyond the Wire About CNW Financials Webcasts Events My CNW All News Releases Add a Filter Gridview Latest News Releases All Today ...

New CmdLets of Powershell 2.0
New CmdLets of Powershell 2.0

Price Drop: Softbox
... objects- create product reflection- changing the background with something more interestingUse it as:- softbox- honeycomb softbox- gridview ...

Profile.aspx: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Quick Answers - CodeProject
Questions - Free source code and tutorials for Software developers and Architects.; Updated: 25 Oct 2012

DotNetKicks.com - Upcoming stories
DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ...

View Features - ExtendASP
Call 847-681-9827 or Request a Demo View Features Testimonials Pricing About Us Coming Soon ExtendASP exposes every feature, more than any other ...

Resources last updated: 12/27/2015 12:29:01 PM