Click here to Skip to main content
15,886,703 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
My .aspx Page
XML
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    onrowupdating="GridView1_RowUpdating" onrowediting="GridView1_RowEditing"
        onrowupdated="GridView1_RowUpdated" onrowcommand="GridView1_RowCommand">
        <Columns>
            <asp:CommandField ShowEditButton="true" ShowDeleteButton="true" ShowInsertButton="true" />
            <asp:TemplateField HeaderText="Id" SortExpression="Id">
                <ItemTemplate>
                    <asp:Label ID="lbl_Id" Text='<%# Bind("id")%>' runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name" SortExpression="Name">
                <ItemTemplate>
                    <asp:Label ID="lbl_name" Text='<%# Bind("Name")%>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txt_name" Text='<%# Bind("Name")%>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address" SortExpression="address">
                <ItemTemplate>
                    <asp:Label ID="lbl_address" Text='<%# Bind("address")%>' runat="server"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txt_address" Text='<%# Bind("address")%>' runat="server"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Label ID="lbl_msg" runat="server"></asp:Label>
</asp:Content>


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseModel;

public partial class _Default : System.Web.UI.Page
{
    DatabaseEntities obj;

    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
    {
        obj = new DatabaseEntities();
        GridView1.DataSource = obj.Records.ToList();
        GridView1.DataBind();
    }
    }
    string data;
    
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
       
    }
    
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
 int index = GridView1.EditIndex;
    GridViewRow row = GridView1.Rows[index];
    Label id = row.FindControl("lbl_Id") as Label;
    int no = Convert.ToInt32(id.Text);
    TextBox t1 = row.FindControl("txt_name") as TextBox;
    TextBox t2 = row.FindControl("txt_address") as TextBox;
    Record rec = obj.Records.First(x => x.Id ==no);
    rec.Name = t1.Text;
    rec.Address = t2.Text;
    obj.SaveChanges();
    
    string t3 = GridView1.DataKeys[e.RowIndex].Value.ToString();

    lbl_msg.Text = "Updated record " + t1.Text + "," + t2.Text;
    }

    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {       
    }
}
Posted
Updated 31-Jul-13 0:17am
v6
Comments
Where is the problem exactly?
Ashish Babu 31-Jul-13 4:54am    
when i am using the code , the value which i am getting is either blank
But i need to access the data which is updated.
I am checking that the data which it is previously fetching is rather getting saved.
Which value is blank and what you expect?
Ashish Babu 31-Jul-13 5:48am    
There is a gridview which shows the id, name and address,
I am editing the name and address in the gridview, but when i am actually fetching the updated data, it is giving only the previously fetched data from the database and not the updated one. My aim is to save the updated data in the gridview to the database.
I have added one answer. Take a look.

I suspect this is a PostBack issue.

So, try keeping the code inside IsPostBack and see what happens.
C#
protected void Page_Load(object sender, EventArgs e)
{
    obj = new DatabaseEntities();

    if(!IsPostBack)
    {
        GridView1.DataSource = obj.Records.ToList();
        GridView1.DataBind();
    }
}
 
Share this answer
 
Comments
Ashish Babu 31-Jul-13 6:18am    
yes u r right, but the id is still not retrievable.
Do like below...
GridViewRow row = GridView1.Rows[e.RowIndex];

And remove the below code.
int index = GridView1.EditIndex;
Ashish Babu 31-Jul-13 6:28am    
but my requirement is to get the id which is in index column
Can't you get the value by the below code?
Label id = row.FindControl("lbl_Id") as Label;
Ashish Babu 31-Jul-13 6:41am    
no, it is giving null value exception
now first past it on Page_load
C#
public void bind()
   {
       string qry = "select Id,Category from  Admin_Category_Software";
       SqlCommand cmd = new SqlCommand(qry, sconn);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       da.Fill(dt);
       GridView1.DataSource = dt;
       GridView1.DataBind();
       GridView1.Columns[1].Visible = false;

   }


next bye Item Template
ASP.NET
<asp:GridView ID="GridView1" runat="server"  Width="684px" CssClass="mGrid" PagerStyle-CssClass="pgr"  AlternatingRowStyle-CssClass="alt" AllowPaging="True" 
              AutoGenerateColumns="False" Font-Bold="True" onrowcommand="GridView1_RowCommand" 
                                onrowdatabound="GridView1_RowDataBound" 
                                onrowdeleting="GridView1_RowDeleting" 
                                onselectedindexchanged="GridView1_SelectedIndexChanged" >

<alternatingrowstyle cssclass="alt"></alternatingrowstyle>

                                          <columns>
                                              <asp:templatefield headertext="Operation">
                                             
                                                  <itemtemplate>
                                                      <asp:linkbutton id="LinkButton2" runat="server" causesvalidation="False">
                                                          CommandArgument='<%# Eval("Id") %>' CommandName="delete" ForeColor="#009900" 
                                                          Text="Delete "></asp:linkbutton>
                                                      <asp:linkbutton id="LinkButton1" runat="server" causesvalidation="False">
                                                          CommandArgument='<%# Eval("Id") %>' CommandName="select" ForeColor="#009900" 
                                                          Text="Update"></asp:linkbutton>
                                                  </itemtemplate>
                                                  <itemstyle width="100px" />
                                              </asp:templatefield>
                                              <asp:templatefield headertext="Id" visible="False">
                                              
                                                  <itemtemplate>
                                                      <asp:label id="Label1" runat="server" text="<%# Eval("Id") %>"></asp:label>
                                                  </itemtemplate>
                                              </asp:templatefield>
                                              <asp:templatefield headertext="Main Category">
                                               
                                                  <itemtemplate>
                                                      <asp:label id="Label2" runat="server" text="<%# Eval("Main_Category") %>"></asp:label>
                                                  </itemtemplate>
                                              </asp:templatefield>
                                              <asp:templatefield headertext="Category">
                                               
                                                 
                                          </asp:templatefield></columns>

<pagerstyle cssclass="pgr"></pagerstyle>

                                          </asp:gridview>



Then On RowCommand
C#
 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       if (e.CommandName == "select")
        {
            Session["Id"] = e.CommandArgument.ToString();
            lblcategoryid.Text = Session["Id"].ToString();

            getdata();
        }
    }

private void getdata()
    {

        String qry1 = "select * from  Admin_Category_Software where Id='" + lblcategoryid.Text.ToString() + "'";
        SqlDataAdapter da1 = new SqlDataAdapter(qry1, sconn);
        DataTable dt1 = new DataTable();
        da1.Fill(dt1);
        if (dt1.Rows.Count == 1)
        {
           
            if (sconn.State == ConnectionState.Open)
            {
                sconn.Close();
            }
            sconn.Open();
            string query = "select * from Admin_Category_Software where Id='" + lblcategoryid.Text.ToString() + "'";
            SqlCommand cmd = new SqlCommand(query, sconn);
            SqlDataReader dr = cmd.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(dr);
            TextBox1.Text = dt.Rows[0][1].ToString();
           
            cmd.ExecuteReader();
            sconn.Close();
          
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, typeof(string), "Alert", "alert('Record is Not Available');", true);

        }
    }
 
Share this answer
 
v2
C#
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;
   }



ASP.NET
<asp:LinkButton ID="LinkButton1" CommandName="update" CommandArgument='<%# Bind("Id") %>' runat="server">Update</asp:LinkButton>
 
Share this answer
 
v2
Comments
Bhupendra Kumar Shukla 31-Jul-13 5:24am    
@jackspero18, Not working...
ArgumentOutOfRangeException is thrown
-Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Ashish Babu 31-Jul-13 5:27am    
@Bhupendra Kumar Shukla
yeah u r right,
ArgumentOutOfRangeException is being thrown .
Ashish Babu 31-Jul-13 6:02am    
@jackspero18
There is a error in the line saying ArgumentOutOfException.

string t3 = GridView1.DataKeys[e.RowIndex].Value.ToString();
After removing the error, same problem is still there, it is fetching previous data.
Ashish Babu 31-Jul-13 6:16am    
@jackspero18
but now i am able to get the id and it is giving null value exception, previously it had been working fine. I am updating the code please have a look at it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900