locked
send row data from webform1 to webform2 display index wise and remove view state row when clicked on remove button? RRS feed

  • Question

  • User-1026236167 posted

    hello here in my code there are some problems 

    when  i want to send row on clicked on edit in webform1 the data is sent to webform 2 and filled textbox  and gridview with billno when clicked on add button   the  billno appears in textbox should be display  in the gridview but you notice that the data fromwhich we get from webform1 row is not display in the view state when we click on add button others adding data is display

    secondly when pass row data from webform1 to webform2 and clicked on remove button there will be error occur in that situation the row is removed 

    webform1
    aspx
    <%@ Page Title="" Language="C#" MasterPageFile="~/Panel/StudentMaster.master" AutoEventWireup="true" CodeFile="gridview.aspx.cs" Inherits="Panel_Default" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
            
                <asp:TemplateField HeaderText="bill no">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("bill_no") %>'></asp:Label>
           
                    </ItemTemplate>
                </asp:TemplateField>
                      <asp:TemplateField  HeaderText="Generate Barcode" >
                                <ItemTemplate>
                                    <a  href="gridview2.aspx?id=<%# Eval("tbl_id") %>">Edit</a>
                                </ItemTemplate>
                            </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <br />
    </asp:Content>
    
    webform1
    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_Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                      
                SqlConnection con = new SqlConnection("server=202.164.35.186;uid=sa;pwd=V$sr3300; database=multiplecompany;Max Pool Size=2000;");
                SqlDataAdapter adp = new SqlDataAdapter("Select * from tbl_sale", con);
                DataTable dt = new DataTable();        
                adp.Fill(dt);
                     
                GridView1.DataSource = dt;
                GridView1.DataBind();
    
    
                }
         }
    }
    
    webform2
    aspx
    
    <%@ Page Title="" Language="C#" MasterPageFile="~/Panel/StudentMaster.master" AutoEventWireup="true" CodeFile="gridview2.aspx.cs" Inherits="Panel_Default" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    
           
                <div class="col-sm-2">
                    <label>Bill No</label>
                    <asp:TextBox  ID="TB_bill_no" runat="server" CssClass="form-control" />
                </div>
    
       
        <asp:GridView ID="GridView2" runat="server" DataKeyNames="tbl_id" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="EmployeeName">
                    <ItemTemplate>
                       <%# Eval("bill_no") %><br />
                       <asp:Button ID="BT_delete" runat="server" Text="X Remove" OnClick="BT_delete_Click" CssClass="btn btn-danger" />               
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    
    
                      <div class="col-sm-2">
                          <label>Add Product</label><br />
                         <asp:Button ID="BT_add" runat="server"  Text="Add +" CssClass="btn btn-primary" OnClick="BT_add_Click" />
                         </div>
    
                      <div class="col-sm-2">
                          <br />
                         <asp:Button ID="Button1" runat="server"  Text="Submit" CssClass="btn btn-primary" OnClick="Button1_Click" />
                         </div>
    
    
    </asp:Content>
    
    webform2
    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_Default : 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 ViewStatetable()
        {
            DataTable DT = new DataTable();
            DT.Columns.Add("bill_no");
            DT.Columns.Add("tbl_id");
            DT.Columns.Add("unit");
            DT.Columns.Add("qty");
            DT.Columns.Add("price");
            DT.Columns.Add("total");
            DT.Columns.Add("discountype");
            DT.Columns.Add("discountvalue");
            DT.Columns.Add("discountamount");
            DT.Columns.Add("taxableamount");
            DT.Columns.Add("taxableactualamount");
            DT.Columns.Add("taxtype");
            DT.Columns.Add("taxpercentage");
            DT.Columns.Add("igstamount");
            DT.Columns.Add("cgstamount");
            DT.Columns.Add("sgstamount");
            DT.Columns.Add("finalamount");
            DT.Columns.Add("size");
            DT.Columns.Add("color");
            DT.Columns.Add("product_name_id");
            DT.Columns.Add("unit_id");
            DT.Columns.Add("size_id");
            DT.Columns.Add("color_id");
            DT.Columns.Add("igst_percentage");
            DT.Columns.Add("cgst_percentage");
            DT.Columns.Add("sgst_percentage");
    
            DT.Columns.Add("barcode");
            ViewState["DT"] = DT as DataTable;
        }
    
    
        public void FillInformation(decimal invoice_id)
        {
            using (Entities ctx = new Entities())
            {
                var cust = (from a in ctx.tbl_sale
                            where a.tbl_id == invoice_id
                            select a).FirstOrDefault();
    
                if (cust != null)
                {
            
                    TB_bill_no.Text = cust.bill_no;
    
                }
    
            }
        }
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
            if (!IsPostBack)
            {
                //if (Request.QueryString["itemid"] != null)
                //{
            
                if (Request.QueryString["id"] != null)
                {
                    decimal invoice_id = Convert.ToDecimal (Request.QueryString["id"].ToString());
                    FillInformation(invoice_id);
    
                    SqlDataAdapter adp = new SqlDataAdapter("select * from tbl_sale where tbl_sale.tbl_id=" + invoice_id.ToString(), connection);
                    DataTable DT = new DataTable();
                    adp.Fill(DT);
    
    
                  //  DT.Rows.Add(TB_bill_no.Text);
    
    
                    GridView2.DataSource = DT;
                    GridView2.DataBind();
    
                }
            
                    ViewStatetable();
                
                    }
    
                }
    
    
        protected void BT_delete_Click(object sender, EventArgs e)
        {
            Button link = (Button)sender;
            GridViewRow row = (GridViewRow)(link.Parent.Parent);
    
            DataTable DT = ViewState["DT"] as DataTable;
            DT.Rows[row.RowIndex].Delete();
            ViewState["DT"] = DT as DataTable;
            GridView2.DataSource = DT;
            GridView2.DataBind();
    
        }
    
      protected void Button1_Click(object sender, EventArgs e)
        {
    
        }
    
        protected void BT_add_Click(object sender, EventArgs e)
        {
            if (ViewState["DT"] != null)
            {
                DataTable DT = ViewState["DT"] as DataTable;
                // decimal tax = 0;
                DT.Rows.Add(TB_bill_no.Text);
    
                GridView2.DataSource = DT;
                GridView2.DataBind();
    
               }
            }
    
    }
    

    Monday, October 12, 2020 7:22 AM

All replies

  • User475983607 posted

    You misunderstand ViewState fundamentals.  ViewState is persisted during post back to the same web Form.  ViewState is gone once the browser navigates to another page which has it's own ViewState.

    I recommend using standard Web Forms programming patterns found in every beginning level tutorial and storing data in a database table not ViewState.   Keep in mind, the GridVew already stores data in ViewState so you're design doubles the amount of data that needs to travels between the client and the server.  Anyway, if you follow standards then all you have to do is pass the ID of the record to the second page because the data is persisted in a table.  Typically the ID is passed in the URL as a querystring parameter.  Very simple.

    Monday, October 12, 2020 12:09 PM
  • User-1026236167 posted

    ok sir i have another problem also in webform 2 i want to apply a condition on Button1_Click where  new record can be added this can insert data in the databse and if record exist in the databse or data get from webform1 on edit click and fill in the textbox of webform2 then  this can update the record not insert similarly two conditions applied exist or not and i want to apply this format in entity framework 6.0 based where u see coding

    webform2 cs

     protected void Button1_Click(object sender, EventArgs e)
        {

          using (Entities ctx = new Entities())
            {
               
                int status = 0;
            
                foreach (GridViewRow row in GridView2.Rows)
                {


                    ctx.tbl_sale.Add(new tbl_sale()
                    {
                        //bill_date = Convert.ToDateTime(TB_purchase_date.Text),
                        // party_id = Convert.ToDecimal(DD_party.SelectedValue.ToString()),
                        bill_no = TB_bill_no.Text,
                    
                    });


                   
                    status = ctx.SaveChanges();

                         }
                    }
            }

    aspx 

        <div class="col-sm-2">
                          <label>Submit</label><br />
                         <asp:Button ID="Button1" runat="server"  Text="Submit" CssClass="btn btn-primary" OnClick="Button1_Click" />
                         </div>

    Tuesday, October 13, 2020 7:56 AM
  • User475983607 posted

    I do not understand the requirements or the code.  It is not possible to get WebForm1 values from WebForm2 unless you executed a server transfer.   Can you explain the high level requirement?  Why are two web forms needed to perform basic CRUD operations?  Are you trying to edit/update a record in a new form?  I do not understand the design and it seems overly complex.

    Tuesday, October 13, 2020 11:32 AM
  • User-1026236167 posted

    sir i want to send webform1 row when clicked on edit button and send to webform2 and fill the textbox with value 

    now the row where we get from webform1 then this will be update when we change textbox with some value and click on submit button update the value 

    and in second case if we add some value in textbox webform2 and click on submit button insert this value in databse

    Tuesday, October 13, 2020 2:45 PM
  • User475983607 posted

    sir i want to send webform1 row when clicked on edit button and send to webform2 and fill the textbox with value

    Get the input values in the EditItem event.  Do a redirect to the WebForm2 with the values.  I would simply pass the ID as explained in your other threads.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewCrud.aspx.cs" Inherits="WebFormsDemo.Gridviews.GridViewCrud" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing">
                    <Columns>
                        <asp:TemplateField HeaderText="UserId" SortExpression="UserId">
                            <EditItemTemplate>
                                <asp:TextBox ID="UserIdEdit" runat="server" Text='<%# Bind("UserId") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="UserIdLabel" runat="server" Text='<%# Bind("UserId") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Username" SortExpression="Username">
                            <EditItemTemplate>
                                <asp:TextBox ID="UsernameEdit" runat="server" Text='<%# Bind("Username") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="UsernameLabel" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Edit/Update" ShowHeader="False">
                            <EditItemTemplate>
                                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
                                &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo.Gridviews
    {
        public partial class GridViewCrud : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if(!Page.IsPostBack)
                {
                    BindData();
                }
            }
            protected void BindData()
            {
                GridView1.DataSource = GetData();
                GridView1.DataBind();
            }
    
            protected DataTable GetData()
            {
                string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT [UserId] ,[Username] FROM[dbo].[Users]"))
                    {
                        cmd.Connection = con;
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataTable dt = new DataTable();
                            sda.Fill(dt);
                            return dt;
                        }
                    }
                }
            }
    
            protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView1.EditIndex = e.NewEditIndex;
                BindData();
    
                string Id = ((TextBox)GridView1.Rows[e.NewEditIndex].FindControl("UserIdEdit")).Text;
                string username = ((TextBox)GridView1.Rows[e.NewEditIndex].FindControl("UsernameEdit")).Text;
    
                Response.Redirect(string.Format("/Gridviews/EditRecord.aspx?id={0}&username={1}", Id, username));
    
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            Label1.Text = "You passed id: " + Request.QueryString["id"] + " and username: " + Request.QueryString["username"];
        }
    }

    now the row where we get from webform1 then this will be update when we change textbox with some value and click on submit button update the value 

    and in second case if we add some value in textbox webform2 and click on submit button insert this value in databse

    I'm not sure what you asking.  I recommend that you set aside time to learn the Web Forms Data Bound control fundamentals rather than learning by trial and error.  Learning the basics is much faster in the long run.

    Tuesday, October 13, 2020 3:49 PM