locked
when click on row then this row data will be updated and when click on topmost row then these data will be updated? RRS feed

  • Question

  • User-1026236167 posted
    hello in my code i have error when clicked on some entry in the listings of demolistings page then the row with its 
    related rows (guid) based fill the data to the example page textbox and gridview if we clicked on the edit button
    on any gridview based row then gridview row data filled to textbox and we change the data the clicked on update
    button then error occur and the topmost entry of guid based will be updated my requirement is why these not effect on
    the those entry we have clicked and if we clicked on first guid entry then they will updated

    demolistings cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; public partial class Panel_demolistings : System.Web.UI.Page { SqlCommand cmd = new SqlCommand(); SqlConnection con = new SqlConnection(); string connection = System.Configuration.ConfigurationManager.AppSettings["con"].ToString(); public void EstablishConnection(string storeprocedure) { con.ConnectionString = connection; cmd.Connection = con; cmd.Connection.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = storeprocedure; } public void CloseConnection() { cmd.Connection.Close(); cmd.Connection.Dispose(); con.Close(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { GetSaleListings(); } } public void GetSaleListings() { SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_demo1", connection); adp.SelectCommand.CommandType = CommandType.Text; DataTable DT = new DataTable(); adp.Fill(DT); Gv1.DataSource = DT; Gv1.DataBind(); } } demolistings aspx <%@ Page Title="" Language="C#" MasterPageFile="~/Panel/StudentMaster.master" AutoEventWireup="true" CodeFile="demolistings.aspx.cs" Inherits="Panel_demolistings" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <div class="row"> <div class="col-lg-12"> <asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-striped table-bordered table-hover" Font-Size="Small" HeaderStyle-BackColor="#343a40" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true"> <Columns> <asp:TemplateField HeaderText="Sr No"> <ItemTemplate> <%# Container.DataItemIndex+1 %> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="name" HeaderText="Name" /> <asp:BoundField DataField="class" HeaderText="Class" /> <asp:BoundField DataField="roll_no" HeaderText="Roll No" /> <asp:TemplateField HeaderText="Edit" > <ItemTemplate> <a href="example.aspx?id=<%# Eval("invoice") %>" >Edit</a> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </div> </asp:Content> example cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; public partial class Panel_example : System.Web.UI.Page { SqlCommand cmd = new SqlCommand(); SqlConnection con = new SqlConnection(); string connection = System.Configuration.ConfigurationManager.AppSettings["con"].ToString(); public void EstablishConnection(string storeprocedure) { con.ConnectionString = connection; cmd.Connection = con; cmd.Connection.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = storeprocedure; } public void CloseConnection() { cmd.Connection.Close(); cmd.Connection.Dispose(); con.Close(); } public void FillInformation(Guid invoice_id) { using (Entities ctx = new Entities()) { var cust = (from a in ctx.tbl_demo1 where a.invoice == invoice_id select a).FirstOrDefault(); if (cust != null) { TB_name.Text = cust.name; TB_age.Text = cust.@class; TB_father_name.Text = cust.roll_no; } } } public void FillViewState() { DataTable DT = new DataTable(); DT.Columns.Add("tbl_id"); DT.Columns.Add("name"); DT.Columns.Add("class"); DT.Columns.Add("roll_no"); // DT.Columns.Add("invoice_id"); ViewState["DT"] = DT; } public DataTable AddNewRow(DataTable DT) { DT.Rows.Add(DT.Rows.Count + 1, TB_name.Text, TB_age.Text, TB_father_name.Text); return DT; } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { FillViewState(); GetRecordID(); if (Request.QueryString["id"] != null) { Guid invoice_id = new Guid(Request.QueryString["id"].ToString()); FillInformation(invoice_id); //BT_add.Text = "Update Record"; SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection); DataTable DT = new DataTable(); adp.Fill(DT); Gv1.DataSource = DT; Gv1.DataBind(); DataTable stu = ViewState["DT"] as DataTable; stu = DT; ViewState["DT"] = stu; } } } protected void BT_add_Click(object sender, EventArgs e) { DataTable DT = ViewState["DT"] as DataTable; if (Request.QueryString["id"] == null) { if (BT_add.Text == "Update Record") { int tbl_id = Convert.ToInt16(TB_ID.Text) - 1; DT.Rows[tbl_id]["name"] = TB_name.Text; DT.Rows[tbl_id]["class"] = TB_age.Text; DT.Rows[tbl_id]["roll_no"] = TB_father_name.Text; //DT.Rows[tbl_id]["invoice_id"] = TB_invoice_id.Text; BT_add.Text = "Add In List"; } else { DT = AddNewRow(DT); } Gv1.DataSource = DT; Gv1.DataBind(); ViewState["DT"] = DT; GetRecordID(); } if (Request.QueryString["id"] != null) { if (BT_add.Text == "Update Record") { foreach (GridViewRow row in Gv1.Rows) { //decimal invoice_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString()); Guid invoice_id = new Guid(Request.QueryString["id"].ToString()); using (Entities ctx = new Entities()) { var package = (from c in ctx.tbl_demo1 where c.invoice == invoice_id select c).FirstOrDefault(); package.name = TB_name.Text; package.@class = TB_age.Text; package.roll_no = TB_father_name.Text; ctx.SaveChanges(); } } } else { DT = AddNewRow(DT); } Gv1.DataSource = DT; Gv1.DataBind(); ViewState["DT"] = DT; GetRecordID(); GetRecordID(); } } protected void BT_save_Click(object sender, EventArgs e) { if (Request.QueryString["id"] == null) { int status = 0; Guid invoice_id = Guid.NewGuid(); foreach (GridViewRow row in Gv1.Rows) { using (Entities ctx = new Entities()) { ctx.tbl_demo1.Add(new tbl_demo1() { name = (Gv1.DataKeys[row.RowIndex].Values["name"].ToString()), @class = (Gv1.DataKeys[row.RowIndex].Values["class"].ToString()), roll_no = (Gv1.DataKeys[row.RowIndex].Values["roll_no"].ToString()), invoice = invoice_id, }); status = ctx.SaveChanges(); } } } if (Request.QueryString["id"] != null) { int status = 0; Guid invoice_id = new Guid(Request.QueryString["id"].ToString()); foreach (GridViewRow row in Gv1.Rows) { decimal tbl_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString()); using (Entities ctx = new Entities()) { var result = ctx.tbl_demo1.SingleOrDefault(b => b.tbl_id == tbl_id); if (result != null) { result.name = TB_name.Text; result.@class = TB_age.Text; result.roll_no = TB_father_name.Text; result.invoice = invoice_id; } status = ctx.SaveChanges(); } } Guid invoice_id1 = new Guid(Request.QueryString["id"].ToString()); foreach (GridViewRow row in Gv1.Rows) { using (Entities ctx = new Entities()) { ctx.tbl_demo1.Add(new tbl_demo1() { name = (Gv1.DataKeys[row.RowIndex].Values["name"].ToString()), @class = (Gv1.DataKeys[row.RowIndex].Values["class"].ToString()), roll_no = (Gv1.DataKeys[row.RowIndex].Values["roll_no"].ToString()), invoice = invoice_id1, }); status = ctx.SaveChanges(); } } } } protected void LB_edit_Click(object sender, EventArgs e) { LinkButton link = (LinkButton)sender; GridViewRow row = (GridViewRow)(link.Parent.Parent); DataTable DT = ViewState["DT"] as DataTable; TB_ID.Text = DT.Rows[row.RowIndex]["tbl_id"].ToString(); TB_name.Text = DT.Rows[row.RowIndex]["name"].ToString(); TB_age.Text = DT.Rows[row.RowIndex]["class"].ToString(); TB_father_name.Text = DT.Rows[row.RowIndex]["roll_no"].ToString(); BT_add.Text = "Update Record"; } public void GetRecordID() { DataTable DT = ViewState["DT"] as DataTable; TB_ID.Text = Convert.ToString(DT.Rows.Count + 1); } protected void LB_remove_Click(object sender, EventArgs e) { if (Request.QueryString["id"] == null) { LinkButton link = (LinkButton)sender; GridViewRow row = (GridViewRow)(link.Parent.Parent); DataTable DT = ViewState["DT"] as DataTable; DT.Rows.RemoveAt(row.RowIndex); for (int i = 0; i < DT.Rows.Count; i++) { DT.Rows[i]["tbl_id"] = i + 1; } Gv1.DataSource = DT; Gv1.DataBind(); ViewState["DT"] = DT; } if (Request.QueryString["id"] != null) { LinkButton link = (LinkButton)sender; GridViewRow row = (GridViewRow)(link.Parent.Parent); DataTable stu = ViewState["DT"] as DataTable; { stu.Rows.RemoveAt(row.RowIndex); for (int i = 0; i < stu.Rows.Count; i++) { stu.Rows[i]["tbl_id"] = i + 1; } decimal tbl_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString()); using (Entities ctx = new Entities()) { tbl_demo1 customer = (from c in ctx.tbl_demo1 where c.tbl_id == tbl_id select c).FirstOrDefault(); ctx.Entry(customer).State = System.Data.Entity.EntityState.Deleted; ctx.SaveChanges(); } Gv1.DataSource = stu; Gv1.DataBind(); ViewState["DT"] = stu; } } } } example aspx <%@ Page Title="" Language="C#" MasterPageFile="~/Panel/StudentMaster.master" AutoEventWireup="true" CodeFile="example.aspx.cs" Inherits="Panel_example" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <div> <asp:HiddenField ID="HiddenField1" runat="server" /> <table> <tr> <td>Record ID</td> <td><asp:TextBox ID="TB_ID" runat="server" Enabled="false" /></td> </tr> <tr> <td>Name</td> <td><asp:TextBox ID="TB_name" runat="server" /></td> </tr> <tr> <td>Age</td> <td><asp:TextBox ID="TB_age" runat="server" /></td> </tr> <tr> <td>Father Name</td> <td><asp:TextBox ID="TB_father_name" runat="server" /></td> </tr> <tr> <td>Invoice ID</td> <td><asp:TextBox ID="TB_invoice_id" runat="server" /></td> </tr> <tr> <td><asp:Button ID="BT_add" runat="server" Text="Add In List" OnClick="BT_add_Click" /></td> <%-- <td><asp:Button ID="tb_update" runat="server" Text="Add In List" OnClick="bt_update_click" /></td>--%> <td><asp:Button ID="BT_save" runat="server" Text="Save Record" OnClick="BT_save_Click" /></td> </tr> </table> <asp:GridView ID="Gv1" runat="server" DataKeyNames="tbl_id, name, class, roll_no" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="tbl_id" HeaderText="tbl_id" /> <asp:BoundField DataField="name" HeaderText="name" /> <asp:BoundField DataField="class" HeaderText="class" /> <asp:BoundField DataField="roll_no" HeaderText="rollno" /> <%-- <asp:BoundField DataField="invoice" HeaderText="invoice_id" />--%> <asp:TemplateField HeaderText="Edit"> <ItemTemplate> <asp:LinkButton ID="LB_edit" runat="server" Text="Edit" OnClick="LB_edit_Click" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Remove"> <ItemTemplate> <asp:LinkButton ID="LB_remove" runat="server" Text="Delete" OnClick="LB_remove_Click" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </asp:Content>
    Monday, November 30, 2020 8:31 AM

Answers

  • User-939850651 posted

    Hi prabhjot1313,

    If you need to add a new record to the Database, you only need do something like:

    protected void BT_add_Click(object sender, EventArgs e)
            {
                DataTable DT = ViewState["DT"] as DataTable;
    
                if (Request.QueryString["invoiceId"] == null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        int tbl_id = Convert.ToInt16(TB_ID.Text) - 1;
                        DT.Rows[tbl_id]["name"] = TB_name.Text;
                        DT.Rows[tbl_id]["class"] = TB_age.Text;
                        DT.Rows[tbl_id]["roll_no"] = TB_father_name.Text;
                        //DT.Rows[tbl_id]["invoice_id"] = TB_invoice_id.Text;
    
                        BT_add.Text = "Add In List";
                    }
                    else
                    {
                        DT = AddNewRow(DT);
                    }
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
    
                if (Request.QueryString["invoiceId"] != null)
                {
                    int RecordId = int.Parse(Session["CurrentRecordId"].ToString());
                    string invoice_id = Request.QueryString["invoiceId"].ToString();
    
                    if (BT_add.Text == "Update Record")
                    {
                        //foreach (GridViewRow row in Gv1.Rows)
                        //{
                        //decimal invoice_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString());
                        //Guid invoice_id = new Guid(Request.QueryString["id"].ToString());
                        using (storeEntities ctx = new storeEntities())
                        {
                            var package = (from c in ctx.tbl_demo1
                                           where c.RecordId == RecordId
                                           select c).FirstOrDefault();
    
                            package.name = TB_name.Text;
                            package.@class = TB_age.Text;
                            package.roll_no = TB_father_name.Text;
    
                            ctx.SaveChanges();
                        }
                        //}
                    }
                    else
                    {
                        //DT = AddNewRow(DT);
                        using (storeEntities ctx = new storeEntities())
                        {
                            ctx.tbl_demo1.Add(new tbl_demo1
                            {
                                name = TB_name.Text,
                                @class = TB_age.Text,
                                roll_no = TB_father_name.Text,
                                invoice = Request.QueryString["invoiceId"],
                                tbl_id = DT.Rows.Count+1
                            });
                            ctx.SaveChanges();
                        }
                    }
                    SqlDataAdapter adp = new SqlDataAdapter("select *  from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection);
                    DT = new DataTable();
                    adp.Fill(DT);
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
            }

    Result:

    As you mentioned, it( AddNewRow() ) only adds data to ViewState, but does not insert records into database tables.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 8, 2020 8:21 AM

All replies

  • User-939850651 posted

    Hi prabhjot1313,

    According to your description, I still don't understand what your current problem is.

    I tried to create an example using the code you provided, but I don’t know the structure of the database table, and I’m not sure if this has any effect on the final result. Even in the process of trying to test, many other problems appeared. Therefore I cannot reproduce your problem correctly.

    If possible, could you clearly describe the current problem and provide the table structure, which will help us solve the current problem.

    Best regards,

    Xudong Peng

    Tuesday, December 1, 2020 7:58 AM
  • User-1026236167 posted

    suppose 

    1) there are some entries in the demolistings page with  (guid) invoice same in all the entries 

    2) when click on edit button all the entries with its related (guid) transfer to example page  

    3) in example page the row where we clicked in demolistings page filled to textbox with its values

    and its related entries filled to the gridview

    4)when we clicked on example page gridview row the its value filled to the textbox

    and we update some value or change value then clicked on update button 

    notice that the any griview row in example page you have clicked not update but the row you have clicked on the demolistings page 

    fill to the example page textbox is update means first row of example page update 

    this is my requirement 

    Tuesday, December 1, 2020 11:39 AM
  • User-939850651 posted

    Hi prabhjot1313,

    Well, I think your problem may be because there is no update datasource bound to the GridView. But the data in the database has indeed been modified.

    The ViewState["DT"] you used has not been updated in this event, so the GridView content has not changed.

    You could try do something like this:

    protected void BT_add_Click(object sender, EventArgs e)
            {
                DataTable DT = ViewState["DT"] as DataTable;
    
                if (Request.QueryString["id"] == null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        int tbl_id = Convert.ToInt16(TB_ID.Text) - 1;
                        DT.Rows[tbl_id]["name"] = TB_name.Text;
                        DT.Rows[tbl_id]["class"] = TB_age.Text;
                        DT.Rows[tbl_id]["roll_no"] = TB_father_name.Text;
                        //DT.Rows[tbl_id]["invoice_id"] = TB_invoice_id.Text;
                        
                        BT_add.Text = "Add In List";
                    }
                    else
                    {
                        DT = AddNewRow(DT);
                    }
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
    
                if (Request.QueryString["id"] != null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        foreach (GridViewRow row in Gv1.Rows)
                        {
                            //decimal invoice_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString());
                            //Guid invoice_id = new Guid(Request.QueryString["id"].ToString());
    //used a string id for testing instead of Guid string invoice_id = Request.QueryString["id"].ToString(); using (storeEntities ctx = new storeEntities()) { var package = (from c in ctx.tbl_demo1 where c.invoice == invoice_id.ToString() select c).FirstOrDefault(); package.name = TB_name.Text; package.@class = TB_age.Text; package.roll_no = TB_father_name.Text; ctx.SaveChanges(); SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection); DT = new DataTable(); adp.Fill(DT); } } } else { DT = AddNewRow(DT); } Gv1.DataSource = DT; Gv1.DataBind(); ViewState["DT"] = DT; GetRecordID(); } }

    Result:

    The above test is based on my guessed data table structure, so I am not sure if this is different from what you expect.

    Best regards,

    Xudong Peng

    Wednesday, December 2, 2020 5:56 AM
  • User-1026236167 posted

    sir normal concept you get

    but when we send the id from demolistings page this will be guid number of entries

    so when we send guid based entries fill to textbox and gridview when we click on gridview edit button and update some entry  so 

    these entry will be update not effect on other

    Wednesday, December 2, 2020 6:51 AM
  • User-939850651 posted

    Hi prabhjot1313,

    I tested the code and in the code you provided:

    using (Entities ctx = new Entities())
          {
           var package = (from c in ctx.tbl_demo1
                          where c.invoice == invoice_id
                          select c).FirstOrDefault();
    
           package.name = TB_name.Text;
           package.@class = TB_age.Text;
           package.roll_no = TB_father_name.Text;
    
           ctx.SaveChanges();
           }

    You only use invoice_id to filter these records and find the first record, which causes you to only update the first data. Similar issues exist in other functions.

    Therefore, I think there are some problems in the design. I recommend that you add a unique identifier ( RecordId ) for each record and pass it to the example page, and use the identifier to identify which record is currently being updated.

    A simple demo:

    demolisting.aspx

    <body>
        <form id="form1" runat="server">
            <div>
                <div class="row">
                    <div class="col-lg-12">
                        <asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="false" Width="100%"
                            CssClass="table table-striped table-bordered table-hover" Font-Size="Small"
                            HeaderStyle-BackColor="#343a40" HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold="true">
                            <Columns>
                                <asp:TemplateField HeaderText="Sr No">
                                    <ItemTemplate>
                                        <%# Container.DataItemIndex+1 %>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="name" HeaderText="Name" />
                                <asp:BoundField DataField="class" HeaderText="Class" />
                                <asp:BoundField DataField="roll_no" HeaderText="Roll No" />
                                <asp:TemplateField HeaderText="Edit">
                                    <ItemTemplate>
                                        <a href="example.aspx?invoiceId=<%# Eval("invoice") %>&recordId=<%# Eval("RecordId") %>">Edit</a>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </div>
                </div>
            </div>
        </form>
    </body>

    example.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    FillViewState();
                    GetRecordID();
                    Session["CurrentRecordId"] = Request.QueryString["recordId"].ToString();
                    if (Request.QueryString["invoiceId"] != null)
                    {
    
                        //Guid invoice_id = new Guid(Request.QueryString["id"].ToString());
                        string invoice_id = Request.QueryString["invoiceId"].ToString();
                        FillInformation(invoice_id);
    
                        //BT_add.Text = "Update Record";
    
                        SqlDataAdapter adp = new SqlDataAdapter("select *  from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection);
    
                        DataTable DT = new DataTable();
                        adp.Fill(DT);
    
                        Gv1.DataSource = DT;
                        Gv1.DataBind();
    
                        DataTable stu = ViewState["DT"] as DataTable;
                        stu = DT;
                        ViewState["DT"] = stu;
                    }
                }
            }

    Take the BT_add_Click event as an example:

    protected void BT_add_Click(object sender, EventArgs e)
            {
                DataTable DT = ViewState["DT"] as DataTable;
    
                if (Request.QueryString["invoiceId"] == null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        int tbl_id = Convert.ToInt16(TB_ID.Text) - 1;
                        DT.Rows[tbl_id]["name"] = TB_name.Text;
                        DT.Rows[tbl_id]["class"] = TB_age.Text;
                        DT.Rows[tbl_id]["roll_no"] = TB_father_name.Text;
                        //DT.Rows[tbl_id]["invoice_id"] = TB_invoice_id.Text;
                        
                        BT_add.Text = "Add In List";
                    }
                    else
                    {
                        DT = AddNewRow(DT);
                    }
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
    
                if (Request.QueryString["invoiceId"] != null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        foreach (GridViewRow row in Gv1.Rows)
                        {
                            //decimal invoice_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString());
                            //Guid invoice_id = new Guid(Request.QueryString["id"].ToString());
                            string invoice_id = Request.QueryString["invoiceId"].ToString();
                            int RecordId = int.Parse(Session["CurrentRecordId"].ToString());
                            using (storeEntities ctx = new storeEntities())
                            {
                                var package = (from c in ctx.tbl_demo1
                                               where c.RecordId == RecordId
                                               select c).FirstOrDefault();
    
                                package.name = TB_name.Text;
                                package.@class = TB_age.Text;
                                package.roll_no = TB_father_name.Text;
    
                                ctx.SaveChanges();
    
                                SqlDataAdapter adp = new SqlDataAdapter("select *  from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection);
                                DT = new DataTable();
                                adp.Fill(DT);
                            }
                        }
                    }
                    else
                    {
                        DT = AddNewRow(DT);
                    }
    
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
            }
    protected void LB_edit_Click(object sender, EventArgs e)
            {
                LinkButton link = (LinkButton)sender;
                GridViewRow row = (GridViewRow)(link.Parent.Parent);
                DataTable DT = ViewState["DT"] as DataTable;
                
                TB_ID.Text = DT.Rows[row.RowIndex]["tbl_id"].ToString();
                TB_name.Text = DT.Rows[row.RowIndex]["name"].ToString();
                TB_age.Text = DT.Rows[row.RowIndex]["class"].ToString();
                TB_father_name.Text = DT.Rows[row.RowIndex]["roll_no"].ToString();
                Session["CurrentRecordId"] = DT.Rows[row.RowIndex]["RecordID"].ToString();
    
                BT_add.Text = "Update Record";
            }

    Result:

    I store the RecordId in the session for testing, you could also store it elsewhere.

    Hope it can help.

    Best regards,

    Xudong Peng

    Friday, December 4, 2020 7:55 AM
  • User-1026236167 posted

    sir all you done is right there is little bit problem 

    as you see provided output in the demolistings page when we click on the edit button the three records transfer to the example page 

    at that situation 3 records already display in the gridview when we click on add in  list button the 4 record is insert in the gridview 

    after 3 records but it is not insert in database it is in [viewstate]  4th record

    so my requirement is the three records as it is which they data hold is update and 4th is insert after 3 records in the database

    the data should not entered double in the database

    Friday, December 4, 2020 12:28 PM
  • User-939850651 posted

    Hi prabhjot1313,

    If you need to add a new record to the Database, you only need do something like:

    protected void BT_add_Click(object sender, EventArgs e)
            {
                DataTable DT = ViewState["DT"] as DataTable;
    
                if (Request.QueryString["invoiceId"] == null)
                {
                    if (BT_add.Text == "Update Record")
                    {
                        int tbl_id = Convert.ToInt16(TB_ID.Text) - 1;
                        DT.Rows[tbl_id]["name"] = TB_name.Text;
                        DT.Rows[tbl_id]["class"] = TB_age.Text;
                        DT.Rows[tbl_id]["roll_no"] = TB_father_name.Text;
                        //DT.Rows[tbl_id]["invoice_id"] = TB_invoice_id.Text;
    
                        BT_add.Text = "Add In List";
                    }
                    else
                    {
                        DT = AddNewRow(DT);
                    }
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
    
                if (Request.QueryString["invoiceId"] != null)
                {
                    int RecordId = int.Parse(Session["CurrentRecordId"].ToString());
                    string invoice_id = Request.QueryString["invoiceId"].ToString();
    
                    if (BT_add.Text == "Update Record")
                    {
                        //foreach (GridViewRow row in Gv1.Rows)
                        //{
                        //decimal invoice_id = Convert.ToDecimal(Gv1.DataKeys[row.RowIndex].Values["tbl_id"].ToString());
                        //Guid invoice_id = new Guid(Request.QueryString["id"].ToString());
                        using (storeEntities ctx = new storeEntities())
                        {
                            var package = (from c in ctx.tbl_demo1
                                           where c.RecordId == RecordId
                                           select c).FirstOrDefault();
    
                            package.name = TB_name.Text;
                            package.@class = TB_age.Text;
                            package.roll_no = TB_father_name.Text;
    
                            ctx.SaveChanges();
                        }
                        //}
                    }
                    else
                    {
                        //DT = AddNewRow(DT);
                        using (storeEntities ctx = new storeEntities())
                        {
                            ctx.tbl_demo1.Add(new tbl_demo1
                            {
                                name = TB_name.Text,
                                @class = TB_age.Text,
                                roll_no = TB_father_name.Text,
                                invoice = Request.QueryString["invoiceId"],
                                tbl_id = DT.Rows.Count+1
                            });
                            ctx.SaveChanges();
                        }
                    }
                    SqlDataAdapter adp = new SqlDataAdapter("select *  from tbl_demo1 where tbl_demo1.invoice='" + invoice_id.ToString() + "'", connection);
                    DT = new DataTable();
                    adp.Fill(DT);
                    Gv1.DataSource = DT;
                    Gv1.DataBind();
                    ViewState["DT"] = DT;
                    GetRecordID();
                }
            }

    Result:

    As you mentioned, it( AddNewRow() ) only adds data to ViewState, but does not insert records into database tables.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 8, 2020 8:21 AM