how to edit,update row in gridview

plz send me sample code for gridview edit and update row.

0
jeevanmummadi
5/1/2008 4:56:42 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

4 Replies
1031 Views

Similar Articles

[PageSpeed] 14

 U can find everything about grid view here..

http://www.gridviewguy.com/CategoryDetails.aspx?categoryID=2_Datagrid,_DataList_and_Repeator_Control 


Hope it helps.

-Manas

=======================================
If this post is useful to you, please mark it as answer.
0
yeotumitsu
5/1/2008 6:30:53 AM

jeevanmummadi:

plz send me sample code for gridview edit and update row.

If using ADO.NET

http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx

If using SqlDataSource

http://www.codersource.net/asp_net_grid_view_whidbey.aspx 

More about Data Access then you can refer here

http://www.asp.net/learn/data-access/

 

Hope that helps! 

 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
5/1/2008 6:47:30 AM
Hi try this code

 

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

<!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 id="Head1" runat="server">
   <title>Grid View Add Update Delete</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
              ShowFooter="true" AllowPaging="true"  PageSize="4"
              AllowSorting="True"
              OnRowCommand="GridView1_RowCommand"
              OnPageIndexChanging="GridView1_PageIndexChanging"
              OnRowDeleting="GridView1_RowDeleting"
              OnRowEditing="GridView1_RowEditing"
              OnRowUpdating="GridView1_RowUpdating"
              OnSorting="GridView1_Sorting"
              OnRowCancelingEdit="GridView1_RowCancelingEdit">
               <Columns>
                 <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                  <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                      <EditItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Eval("Id") %>'></asp:Label>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label1" runat="server"
Text='<%# Bind("Id") %>'></asp:Label>
                      </ItemTemplate>
                  </asp:TemplateField>
                   <asp:BoundField DataField="Id"  ShowHeader="True"/>
                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("Name") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label2" runat="server"
 Text='<%# Bind("Name") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField HeaderText="Description" SortExpression="Description">
                      <EditItemTemplate>
                          <asp:TextBox ID="TextBox2" runat="server"
Text='<%# Bind("Description") %>'></asp:TextBox>
                      </EditItemTemplate>
                      <ItemTemplate>
                          <asp:Label ID="Label3" runat="server"
Text='<%# Bind("Description") %>'></asp:Label>
                      </ItemTemplate>
                      <FooterTemplate>
                          <asp:TextBox ID="DescriptionTextBox" runat="server"></asp:TextBox>
                      </FooterTemplate>
                  </asp:TemplateField>
                  <asp:TemplateField>
                     <FooterTemplate>
                          <asp:LinkButton ID="btnNew" runat="server"
CommandName="New" Text="New" />
                      </FooterTemplate>
                  </asp:TemplateField>
              </Columns>
          </asp:GridView>
       </div>
       <div style="color:Red">
       <asp:Label ID="lblMsg" runat="server"></asp:Label>
       </div>
   </form>
</body>
</html>
   
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;


public partial class GridViewComplete : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        {
            BindGrid();
          
        }
    }
    public void BindGrid()
    {


        if (Session["dt"] == null)
        {
            GridView1.DataSource = CreateDGDataSource();
            GridView1.DataBind();
        }
        else
        {

            GridView1.DataSource = Session["dt"] as DataTable;
            GridView1.DataBind();

        }



    }
    public DataTable CreateDGDataSource()
    {
        // Create sample data for the DataList control.
        DataTable dt = new DataTable();
        DataRow dr;
        int i;
        int y;
        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("ID", typeof(int)));
        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        //Make some rows and put some sample data in
        for (i = 1; i <= 5; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Name" + "-" + i;
            dr[2] = "Item " + "_" + i;
            //add the row to the datatable
            dt.Rows.Add(dr);
        }

        Session["y"] = i;
        Session["dt"] = dt;

        return dt;
    }

    public ICollection CreateDGDataSource(int CategoryID)
    {
        DataView dv = new DataView(CreateDGDataSource(), "ID=" + CategoryID, null,
            DataViewRowState.CurrentRows);
        return dv;

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.Equals("New"))
            {
                LinkButton btnNew = e.CommandSource as LinkButton;
                GridViewRow row = btnNew.NamingContainer as GridViewRow;
                if (row == null)
                {
                    return;
                }
                TextBox txtCatName = row.FindControl("QuantityTextBox") as TextBox;
                TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;
                DataTable dt = Session["dt"] as DataTable;
                DataRow dr;
                int intId = (int)Session["y"];
                dr = dt.NewRow();
                dr["Id"] = intId++;
                Session["y"] = intId;
                dr["Name"] = txtCatName.Text;
                dr["Description"] = txtDescription.Text;
                dt.Rows.Add(dr);
                dt.AcceptChanges();
                Session["dt"] = dt;

                GridView1.DataSource = Session["dt"] as DataTable;
                GridView1.DataBind();

            }

        }
        catch (Exception ex)
        {

        }


    }
   
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = Session["dt"] as DataTable;
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
            GridView1.DataSource = dataView;
            GridView1.DataBind();
        }
    }
    private string ConvertSortDirectionToSql(SortDirection sortDireciton)
    {
        string newSortDirection = String.Empty;
        switch (sortDireciton)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;
            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }
        return newSortDirection;
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
        // Query the database and get the values based on the ID and delete it.
        lblMsg.Text = "Deleted Record Id" +ID.ToString();
      
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
       
        // Retrieve the row being edited.
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
        TextBox t1 = row.FindControl("TextBox1") as TextBox;
        TextBox t2 = row.FindControl("TextBox2") as TextBox;
        string t3 = GridView1.DataKeys[e.RowIndex].Value.ToString();

        lblMsg.Text = "Updated record " + t1.Text + "," + t2.Text + "Value From Bound Field" + t3;
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindGrid();
    }
}
 
Santosh kumar
Mark as Answer on the post that helped you.



Blog
0
santosh
5/1/2008 7:22:58 AM

Thanks for sharing your code, Santosh - this is of great help!

I was challenged by my boss to populate a gridview that would make some rows to become in editable mode (in a bundle) if a field (let's say RowIsEditable) value in the gridview itself is 1 (true) or 0 (false) respectively. I know how to setup so that all the rows can become in editable mode but how can I accomplish this for individual rows?

Thanks in advance! Smile 

Gilberto 

0
gbeltrao
5/23/2008 4:59:10 AM
Reply:

Similar Artilces:

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 : How to Edit the row in Gridview (update)
I have Gridview in which I'm displaying the row, I wanted to update/Modify the row  using custom button not with the link 'Edit' when I enable AutoGenerateEditButton ="true" Whenever user clicks on the Button, (ImageButton), it has to fire the event 'Gridview1_RowEditing'  Any help on this will be appreciated.    Your ImageButton simply needs to have its CommandName property set to "Edit".Thanks, EdMicrosoft MVP - ASP/ASP.NET  I am using one such logic, <asp:TemplateField HeaderText="Edit" Show...

After hitting update on gridview, data changes but gridview still shows the update and cancel links for edited row
Really weird. I click the update link after I change the input data. I debug through it and it shows that the update is complete but then when OnRowUpdating function is done the update and cancel links are still there. What else do I need to do.. Here is the code. ASP:  <asp:GridView ID="OOWSecAuth" runat="server" AutoGenerateColumns="false" ShowFooter="true" AutoGenerateEditButton="true" OnRowEditing="OOWSecAuthEdit" OnRowUpdating="OOWSecAuthUpdate" ...

Updating and binding control to other controls within the same row of a GridView
HiIn the EditTemplate of my GridView I show 2 DropDownLists. When the user selects the first dropdownlist, I need it to update the contents of the second dropdownlist. I have my Subs that do this fine when not inside the GridView, but what is the correct way to do it whilst they are in the GridView?This is my current attempt that returns the error 'Object reference not set to an instance of an object'. I presume its related to correctly targeting the DropDownList in question? This is my GridView:<asp:GridView ID="GridView1" runat="server"  &...

GridView : how to Highlight the last edited Row in gridview and update Dropdrown
never mine i solve the prob. thanks Hi there,I think you are determining the edited row as:int index = GridView1.EditIndex;After finishing the update you must doing GridView1.DataBind();With in your update procedure last statement should be:GridView1.SelectedIndex = index;If you want to update the dropdown just say:DropDownList1.Items.Clear();DropDownList1.DataBind();Hope this helps,thanks,Murthy here Dont forget to click "Mark as Answer" on the post that helped you. This credits that member, earns you a point and marks your thread as Resolved so we will all know you have be...

why can't Gridview update if empty data is presented into the textfield of Gridview edit
 HI all,I have basically two fields which are Name,description. Whenever I was trying to edit fields(name, description) the command event is not firing because description(textbox) is empty. Why and how to fix this issuse. Because Name field is a required one and description is optional it could be empty one. Any help please thanks and regards,Vijaycanaan.  Can you please give your code. This can help us understand and solve your problem!! Here is the code   <asp:GridView ID="GridView1" runat="server" AllowPaging="True" Aut...

edit and update a gridview control
Hi, Here's my question: The gridview shows all the items the student has already learned. Can the gridview be updated to add new data? For instance, the user wants to add another piece of item to learn and give a brief reason? I will add the dropdownlist and textbox control to the gridview (in edit mode, I assume)The dropdownlist will be bound to a datasource. Once the user has made a selection and typed a reason in the textbox, they will update the gridview to show what they have done. AFter they see that, they click a button which will launch a new page with the gridvi...

GridView does not update editable row
Hello I have used a gridview control to list and edit some items on the list. I have turned on the "Enable Editing" mode on the Gridview but the data is not updated when it comes to editable view. Instead it returns with original data as there is no change on the items. My code is like the one below: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="MasrafDetayId" DataSourceID="SqlDataSource1"><Columns><asp:CommandField ShowEditButton="True" /><asp:BoundField DataField="MasrafDetayId" HeaderText="MasrafDetayId" InsertVisi...

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 do I fix a Edit GridView Error
Hello, I keep getting this error when I edit and update a gridview.   Server Error in '/Albers_website' Application. Updating is not supported by data source 'SqlHAPSource' unless UpdateCommand is specified. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NotSupportedException: Updating is not supported by data source 'SqlHAPSource' unless UpdateCommand is specified.Source Error: [NotSupporte...

Update a gridview row without edit
Hi! I work with C # I want update my columns in my GridView without going through edit : for each row I click update button to update the line how? Thank you. This is easy enough to do. First, you need to add your input controls into TemplateFields instead of BoundFields. Secondly, you then need to add your own Update Button within another TemplateField setting the CommandName property to something of your choosing. Next, capture this event within the the GridView.RowCommand handler and update your row accordingly.Thanks, EdMicrosoft MVP - ASP/ASP.NET Check this article t...

Urgent!!! Edit and Update all rows in Gridview
Hi All, I am  a newbie to the  ASP.NET  and i want to know how to Edit  all rows (instead of row by row when user clicks Edit button on gridview) .After Editing all rows  and when the user clicks the Save button i want to update all the rows which the user has modified..please can any body tell me the  procedure how to do this. i am using ASP.NET 2.0 with VB.NET  and  using Oracle  8i  Database..my gridview contains more than 100 records.  thanks in advance..  function __RP_Callback_Helper(str, strCallbackEvent, splitSize,...

Multiple Row Editing and Updating on Gridview
I have a gridview control which display data using SQL Data reader depending on users search criteria. I want users to edit and update multiple or single entries on gridview, how can I make this possbile? any good example I can follow? How can records received from Sql Data Reader  displayed on gridview directly in editing mode.       To do any sort of editing you will need to switch from a DataReader to a DataSet.  A data reader is a forward only, read only way to access data.  Using a dataset, you can very easily update a row at a time.&nb...

Edit Button update all rows from a GridView
Can i make a Gridview which has only 1 edit button and when i click it specific fields from all rows become editable? If ai can't use the gridview can u tell if another asp control is capable of doing that? The Real World GridView does just that......

Web resources about - how to edit,update row in gridview - asp.net.presentation-controls

Facebook IOS App Users Can Now Edit Posts, Comments Following Update
The ability to edit posts and comments was the most significant addition to version 6.6 of Facebook’s iOS application , which was rolled out ...

Android, web update allows Facebook users to edit posts
... users could edit their own comments , but there was no way to go back to fix a typo or mistake in a post without deleting it. An update for ...

DECEPTIVE EDIT UPDATE: NBC Producer Fired, But Still Unnamed. Unnamed? Come on. The public has a…
DECEPTIVE EDIT UPDATE: NBC Producer Fired, But Still Unnamed. Unnamed? Come on. The public has a right to know!

Updates for Google Docs & Slides let you insert & quickly edit images on Android/iOS
Google is today rolling out updates to its Google Docs and Slides mobile apps bringing the ability to insert images directly from the app on ...

Updates to Google Docs & Slides let you insert & quickly edit images on iOS
... a new photo to insert directly into a document or Slides presentation. In addition, the update includes quicker access to make basic edits ...

Facebook For IOS Gets Structured Status Updates, Ability To Edit Privacy Settings Of Shared Content ...
... status updates that were previously available only on desktop or via the social network’s mobile site, as well as the ability to edit who can ...

Facebook app update now lets you edit posts
... updated its Android app. And while there's no actual changelog yet — Facebook's still really bad about that for some reason — you can now edit ...

Gmail Update Highlighted By Edit Mode For Multiple Messages
Google has just updated its Gmail app for iOS with the addition of two nice features. First up, version 2.1 of the app ushers in the new edit ...

Sony's new PS4 update makes it easier for gamers to edit and share videos
... details are beginning to trickle out about what customers can expect from the update, the biggest of which seems to be a new method for editing ...

AOL Updates Kanvas, Turns it Into a Live Streaming App You Can Edit on the Fly
... ), an app that let you post video, pictures, and gifs decorated with stickers and animations. The new 5.0 release , the first major update post-buyout, ...

Resources last updated: 11/25/2015 7:02:43 PM