Monday 30 December 2013

GridView Insert,Update,Edit and Delete in C#.net

On .aspx Page:

<asp:GridView ID="gvDetails"  runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"ImageUrl="~/Images/update.png" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"ImageUrl="~/Images/Cancel.png" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.png"ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server"ImageUrl="~/Images/delete.png" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User"ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*"ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*"ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>


 



After that on .cs File:


SqlConnection con = new SqlConnection("Data Source=BRIJESH-PC;Integrated Security=true;Initial Catalog=TEST");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}

Saturday 7 December 2013

Export Selected GridViewRow to Excel on button click in C#.NET

Copy & Paste this on .aspx file:

<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" CellPadding="4"
                            BackColor="#5DA63A" ForeColor="White" Width="100%" AllowPaging="false" Style="border-radius: 10px;
                            border: Solid 3px #5DA63A; text-align: left; word-wrap: break-word; word-break: break-all">
                            <AlternatingRowStyle BackColor="#F1FCCA"></AlternatingRowStyle>
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" CssClass="grid_font" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#8EBE12" Font-Bold="False" ForeColor="#E7E7FF" />
                            <Columns>
                                <asp:TemplateField ItemStyle-Width="20px">
                                    <HeaderTemplate>
                                        <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" 
                                            oncheckedchanged="chkAll_CheckedChanged" />
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="True" 
                                            oncheckedchanged="chkSelect_CheckedChanged" />
                                    </ItemTemplate>
                                    <ItemStyle Width="20px" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="EIEUID" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblid" runat="server" Text='<%#Eval("EIEUid")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="60px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblname" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="150px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Details" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblemail" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="160px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Mobile" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblmobile" runat="server" Text='<%#Eval("Mobile")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="120px" />
                                    </asp:TemplateField>
                            </Columns>
                        </asp:GridView>



Copy & Paste this on .cs Code File:

dataUtility du = new dataUtility();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindGridData();
        }

        /// This Method is used to bind gridview
        private void BindGridData()
        {
            try
            {
                DataTable dtnew = new DataTable();
                DataTable dt = new DataTable();
                dt = du.executeStoteProc("SP_CLIENT 5,'" + Session["Name"] + "','',''");
               
                    if (dt.Rows.Count > 0)
                    {
                        gvDetails.DataSource = dt;
                        gvDetails.DataBind();

                    }
                    else
                    {
                        dt.Rows.Add(dt.NewRow());
                        gvDetails.DataSource = dt;
                        gvDetails.DataBind();
                        int columncount = gvDetails.Rows[0].Cells.Count;
                        gvDetails.Rows[0].Cells.Clear();
                        gvDetails.Rows[0].Cells.Add(new TableCell());
                        gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
                        gvDetails.Rows[0].Cells[0].Text = "No Records Found";
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }

        /// enable gridview control to be rendered
        public override void VerifyRenderingInServerForm(Control control)
        {
            /*Verifies that the control is rendered */
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            ExportToExcell();
        }

        /// export gridview to excel
        private void ExportToExcell()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Details");
            dt.Columns.Add("Mobile");
            foreach (GridViewRow row in gvDetails.Rows)
            {
                CheckBox chkCalls = (CheckBox)row.FindControl("chkSelect");
                if (chkCalls.Checked == true)
                {
                    int i = row.RowIndex;
                    Label lblname = (Label)gvDetails.Rows[i].FindControl("lblname");
                    Label lblemail = (Label)gvDetails.Rows[i].FindControl("lblemail");
                    Label lblmobile = (Label)gvDetails.Rows[i].FindControl("lblmobile");

                    DataRow dr = dt.NewRow();
                    dr["Name"] = Convert.ToString(lblname.Text);
                    dr["Details"] = Convert.ToString(lblemail.Text);
                    dr["Mobile"] = Convert.ToString(lblmobile.Text);
                    dt.Rows.Add(dr);
                }
            }
            GridView gdvExportxls = new GridView();
            gdvExportxls.DataSource = dt;
            gdvExportxls.DataBind();
            gdvExportxls.HeaderStyle.Font.Bold = true;
            gdvExportxls.HeaderStyle.ForeColor = Color.White;
            gdvExportxls.HeaderStyle.BackColor = Color.Green;
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("content-disposition", string.Format("attachment;filename=ReferrerDetails.xls", "selectedrows"));
            Response.Charset = "";
            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
            gdvExportxls.RenderControl(htmlwriter);
            Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
            Response.End();

        }

        /// select/unselect all row using header checkbox
        protected void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox chkH = (CheckBox)gvDetails.HeaderRow.FindControl("chkAll");
                if (chkH.Checked == true)
                {
                    foreach (GridViewRow gv in gvDetails.Rows)
                    {
                        CheckBox chk = (CheckBox)gv.FindControl("chkSelect");
                        chk.Checked = true;
                    }
                }
                else
                {
                    foreach (GridViewRow gv in gvDetails.Rows)
                    {
                        CheckBox chk = (CheckBox)gv.FindControl("chkSelect");
                        chk.Checked = false;
                    }

                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        /// select/unselect single row using row checkbox
        protected void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            bool isFound = false;
            CheckBox cbxall = (CheckBox)gvDetails.HeaderRow.FindControl("chkAll");
            foreach (GridViewRow gvr in gvDetails.Rows)
            {
                CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
                if (chkSelect.Checked == false)
                {
                    isFound = true;
                    break;
                }

            }

            if (isFound)
                cbxall.Checked = false;
            else
                cbxall.Checked = true;

        }

Thursday 5 December 2013

SOLVED: Session Lost problem after Response.Redirect when redirect from Iframe

Copy & Paste this to head tag:

<script type="text/javascript" language="javascript">
      
        //for Redirect Iframe
        function Redirect() 
        {
            top.location = "Checkout.aspx";
            return false;
        }

</script>


Copy & Paste this code on .cs file:

ScriptManager.RegisterStartupScript(Page, typeof(System.Web.UI.Page),
                                                    "blur", @"<script type='text/javascript'>Redirect();</script>", false);

Note: bool value set true if you don't use UpdatePanel......

How To Style A Checkbox With CSS

Method 1:

/* in style tag */

.onoffswitch {
    position: relative; width: 65px;
    -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
    display: none;
}
.onoffswitch-label {
    display: block; overflow: hidden; cursor: pointer;
    border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
    width: 200%; margin-left: -100%;
    -moz-transition: margin 0.3s ease-in 0s; -webkit-transition: margin 0.3s ease-in 0s;
    -o-transition: margin 0.3s ease-in 0s; transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
    float: left; width: 50%; height: 25px; padding: 0; line-height: 25px;
    font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
    -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
}
.onoffswitch-inner:before {
    content: "ON";
    padding-left: 10px;
    background-color: #FFC42F; color: #FFFFFF;
}
.onoffswitch-inner:after {
    content: "OFF";
    padding-right: 10px;
    background-color: #EEEEEE; color: #999999;
    text-align: right;
}
.onoffswitch-switch {
    width: 15px; margin: 5px;
    background: #FFFFFF;
    border: 2px solid #999999; border-radius: 20px;
    position: absolute; top: 0; bottom: 0; right: 36px;
    -moz-transition: all 0.3s ease-in 0s; -webkit-transition: all 0.3s ease-in 0s;
    -o-transition: all 0.3s ease-in 0s; transition: all 0.3s ease-in 0s; 
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
    margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
    right: 0px; 
}

/* html tag */

<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch">
    <label class="onoffswitch-label" for="myonoffswitch">
        <div class="onoffswitch-inner"></div>
        <div class="onoffswitch-switch"></div>
    </label>
</div>




Method 2:

/* in style tag */

.slideThree {
width: 80px;
height: 26px;
background: #333;
margin: 20px auto;

-webkit-border-radius: 50px;
-moz-border-radius: 50px;
border-radius: 50px;
position: relative;

-webkit-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
-moz-box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
box-shadow: inset 0px 1px 1px rgba(0,0,0,0.5), 0px 1px 0px rgba(255,255,255,0.2);
}

.slideThree:after {
content: 'OFF';
font: 12px/26px Arial, sans-serif;
color: #000;
position: absolute;
right: 10px;
z-index: 0;
font-weight: bold;
text-shadow: 1px 1px 0px rgba(255,255,255,.15);
}

.slideThree:before {
content: 'ON';
font: 12px/26px Arial, sans-serif;
color: #00bf00;
position: absolute;
left: 10px;
z-index: 0;
font-weight: bold;
}

.slideThree label {
display: block;
width: 34px;
height: 20px;

-webkit-border-radius: 50px;
-moz-border-radius: 50px;
border-radius: 50px;

-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
-o-transition: all .4s ease;
-ms-transition: all .4s ease;
transition: all .4s ease;
cursor: pointer;
position: absolute;
top: 3px;
left: 3px;
z-index: 1;

-webkit-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
-moz-box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.3);
background: #fcfff4;

background: -webkit-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -moz-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -o-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: -ms-linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
background: linear-gradient(top, #fcfff4 0%, #dfe5d7 40%, #b3bead 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfff4', endColorstr='#b3bead',GradientType=0 );
}

.slideThree input[type=checkbox]:checked + label {
left: 43px;
}


/* html tag */

<div class="slideThree">
<input type="checkbox" value="None" id="slideThree" name="check" />
<label for="slideThree"></label>
</div>



Monday 2 December 2013

HOw to Add break-point when Debug Window Service in C#.net

Service1.cs file code:

Timer timer;
        public Service1()
        {
            InitializeComponent();
        }

        public void OnDebug()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            // get today's date at 00:01 AM  
            DateTime time = DateTime.Today.AddMinutes(1);

            // if 00:01 AM has passed, get tomorrow at 00:01 AM  
            if (DateTime.Now > time)
                time = time.AddDays(1);

            // calculate milliseconds until the next 00:01 AM.  
            int timeToFirstExecution = (int)time.Subtract(DateTime.Now).TotalMilliseconds;

            // calculate the number of milliseconds in 24 hours.   
            int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;

            // set the method to execute when the timer executes.   
            TimerCallback methodToExecute = Brijeshmethod;

            // start the timer.  The timer will execute "Brijeshmethod" when the number of seconds between now and   
            // the next 00:01 AM elapse.  After that, it will execute every 24 hours.   
            timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls);
  
        }

        private void Brijeshmethod(object source)
        {
            //write your code here
        }

        protected override void OnStop()
        {
            Thread.Sleep(Timeout.Infinite);

        }



Program file:

/// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            #if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            #else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
            #endif


        }