Wednesday, 20 March 2013

nested grideview and transaction use in asp.net

page looks like




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Transaction="Supported" %>

<!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></title>
 
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <div>
    <asp:UpdatePanel ID="up" runat="server">
    <ContentTemplate>
    <table align="center">
    <tr><td>EID</td><td><asp:TextBox ID="tb" runat="server"></asp:TextBox></td></tr>
     <tr><td>NAME</td><td><asp:TextBox ID="tb1" runat="server"></asp:TextBox></td></tr>
      <tr><td>DEPARTMENT NAME</td><td><asp:DropDownList ID="ddl" runat="server"></asp:DropDownList>&nbsp;<asp:Button
              ID="btn" runat="server" Text="Add More" onclick="btn_Click" /></td></tr>
      <tr><td>&nbsp;</td><td><asp:GridView ID="gv" runat="server" DataKeyNames="did"
              AutoGenerateColumns="false" onrowcancelingedit="gv_RowCancelingEdit"
              onrowdeleting="gv_RowDeleting" onrowediting="gv_RowEditing"
              onrowupdating="gv_RowUpdating" >
          <Columns>
              <asp:CommandField HeaderText="UPDATE" ShowEditButton="True" ShowHeader="True" />
              <asp:CommandField HeaderText="DELETE" ShowDeleteButton="True" ShowHeader="True" />
             <asp:BoundField HeaderText="DID" DataField="DID" ReadOnly="true" />
             <asp:TemplateField HeaderText="DNAME">
             <ItemTemplate>
             <asp:Label ID="lb" runat="server" Text='<%#Eval("dname") %>'></asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList>
             </EditItemTemplate>
             </asp:TemplateField>
          </Columns>
          </asp:GridView></td></tr>
      <tr><td>&nbsp;</td><td><asp:Button ID="btn1" runat="server" Text="Save" Width="80"
              onclick="btn1_Click" /></td></tr>
       <tr><td>&nbsp;</td><td>
       <asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false"
               onselectedindexchanging="gv1_SelectedIndexChanging">
       <Columns>
       <asp:TemplateField>
      <HeaderTemplate>
      <table>
      <tr><td>SELECT</td><td>EID</td><td>NAME</td></tr>
      </HeaderTemplate>
      <ItemTemplate>
      <tr><td><asp:LinkButton ID="lbtn" runat="server" Font-Underline="false" Text="+" CommandName="select" CommandArgument='<%#Eval("id") %>'></asp:LinkButton></td><td><%#Eval("id") %></td><td><%#Eval("name") %></td></tr>
      <tr><td colspan="3">
      <asp:GridView ID="gv2" runat="server" Width="100%" Visible="false"></asp:GridView>
 </td></tr>
      </ItemTemplate>
      <FooterTemplate>
      </table>
      </FooterTemplate>
       </asp:TemplateField>
       </Columns>
       </asp:GridView>
       </td></tr>
     
    </table>
    </ContentTemplate>
    </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>
c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TestModel;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    #region
    TestEntities te = new TestEntities();
    DataTable dt = new DataTable();
    SqlConnection cn;
    SqlCommand cm;
    SqlTransaction st;
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<DEPT1> p = new List<DEPT1>();
            DEPT1 o = new DEPT1();
            o.DID = 0;
            o.DNAME = "Select";
            p.Add(o);
            ddl.DataSource = p.Union(te.DEPT1);
            ddl.DataTextField = "dname";
            ddl.DataValueField = "did";
            ddl.DataBind();
            fill();
            ViewState["i"] = 0;
        }
       
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        dt.Columns.Add("DID", typeof(string));
        dt.Columns.Add("DNAME", typeof(string));
        DataRow dr;
        dr = dt.NewRow();
        dr[0] = ddl.SelectedValue.ToString();
        dr[1] = ddl.SelectedItem.Text;
        dt.Rows.Add(dr);
        foreach (GridViewRow gvr in gv.Rows)
        {
            dr = dt.NewRow();
            dr[0] = gvr.Cells[2].Text;
            dr[1] = ((Label)gvr.Cells[3].FindControl("lb")).Text;
            dt.Rows.Add(dr);
        }
        gv.DataSource = dt;
        gv.DataBind();
        ViewState["dt"] = dt;
    }
    protected void gv_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gv.EditIndex = -1;
        gv.DataSource = (DataTable)ViewState["dt"];
        gv.DataBind();
    }
    protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gv.EditIndex = e.NewEditIndex;
        gv.DataSource = (DataTable)ViewState["dt"];
        gv.DataBind();
        List<DEPT1> p = new List<DEPT1>();
        DEPT1 o = new DEPT1();
        o.DID = 0;
        o.DNAME = "Select";
        p.Add(o);
        ((DropDownList)gv.Rows[e.NewEditIndex].Cells[3].FindControl("ddl1")).DataSource = p.Union(te.DEPT1);
        ((DropDownList)gv.Rows[e.NewEditIndex].Cells[3].FindControl("ddl1")).DataTextField = "dname";
        ((DropDownList)gv.Rows[e.NewEditIndex].Cells[3].FindControl("ddl1")).DataValueField = "did";
        ((DropDownList)gv.Rows[e.NewEditIndex].Cells[3].FindControl("ddl1")).DataBind();
        ((DropDownList)gv.Rows[e.NewEditIndex].Cells[3].FindControl("ddl1")).SelectedValue = Convert.ToInt32(gv.DataKeys[e.NewEditIndex].Value).ToString();
    }
    protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        ((DataTable)ViewState["dt"]).Rows[e.RowIndex][0] = ((DropDownList)gv.Rows[e.RowIndex].Cells[3].FindControl("ddl1")).SelectedValue;
        ((DataTable)ViewState["dt"]).Rows[e.RowIndex][1] = ((DropDownList)gv.Rows[e.RowIndex].Cells[3].FindControl("ddl1")).SelectedItem.Text;
        ViewState["dt"] = ((DataTable)ViewState["dt"]);
        gv.EditIndex = -1;
        gv.DataSource = (DataTable)ViewState["dt"];
        gv.DataBind();

    }
    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ((DataTable)ViewState["dt"]).Rows.RemoveAt(e.RowIndex);
        ViewState["dt"] = ((DataTable)ViewState["dt"]);
        gv.DataSource = (DataTable)ViewState["dt"];
        gv.DataBind();

    }
    void fill()
    {
        gv1.DataSource = te.EMPs.ToList();
        gv1.DataBind();
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        try
        {
            cn = new SqlConnection("server=SWASH-DBS\\SWASHSQLINT;database=test;uid=ken;pwd=kc@2011");
            cn.Open();
            st = cn.BeginTransaction();
            cm = new SqlCommand("insert into emp values(" + tb.Text + ",'" + tb1.Text + "')", cn);
            cm.Transaction = st;
            cm.ExecuteNonQuery();
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                cm = new SqlCommand("insert into empdetails(eid,did) values(" + tb.Text + "," + gv.Rows[i].Cells[2].Text + ")", cn);
                cm.Transaction = st;
                cm.ExecuteNonQuery();
            }
            st.Commit();
            ScriptManager.RegisterStartupScript(this, GetType(), "x", "alert('One record saved.')", true);
            fill();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "x", "alert('" + ex.Message + "')", true); ;
            st.Rollback();
        }
    }
    protected void gv1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        if (Convert.ToInt32(ViewState["i"]) == 0)
        {
            int j = 0;
            j = Convert.ToInt32(((LinkButton)gv1.Rows[e.NewSelectedIndex].FindControl("lbtn")).CommandArgument);
            var m = (from x in te.EMPDETAILS
                     join y in te.DEPT1
                     on x.DID equals y.DID
                     where x.EID == j
                     select new { y.DNAME }).ToList();
            ((GridView)gv1.Rows[e.NewSelectedIndex].FindControl("gv2")).Visible = true;
            ((GridView)gv1.Rows[e.NewSelectedIndex].FindControl("gv2")).DataSource = m;
            ((GridView)gv1.Rows[e.NewSelectedIndex].FindControl("gv2")).DataBind();
            ((LinkButton)gv1.Rows[e.NewSelectedIndex].FindControl("lbtn")).Text = "-";
            ViewState["i"] = 1;
        }
        else
        {
            ((LinkButton)gv1.Rows[e.NewSelectedIndex].FindControl("lbtn")).Text = "+";
            ((GridView)gv1.Rows[e.NewSelectedIndex].FindControl("gv2")).Visible = false;
            ViewState["i"] = 0;
        }

    }
}

No comments:

Post a Comment