Wednesday, July 15, 2015

Adding Dynamic Rows in GridView with DropDownLists in ASP.Net

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
//using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Specialized;

namespace autorowgenaration
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private ArrayList ddlist()
        {
            ArrayList arl = new ArrayList();
            arl.Add(new ListItem("feel", "1"));
            arl.Add(new ListItem("feel2", "2"));
            return arl;

        }
        private void fildrop(DropDownList ddl)
        {
            ArrayList arl = ddlist();
            foreach (ListItem item in arl)
            {
                ddl.Items.Add(item);
            }
        }
        protected void setfirstrow()
        {
            DataTable dt = new DataTable();
            DataRow dr = null;
            dt.Columns.Add(new DataColumn("rowno", typeof(string)));
            dt.Columns.Add(new DataColumn("col1", typeof(string)));
            dt.Columns.Add(new DataColumn("col2", typeof(string)));
            dt.Columns.Add(new DataColumn("col3", typeof(string)));
            dt.Columns.Add(new DataColumn("col4",typeof(string)));
            dr = dt.NewRow();
            dr["rowno"] = 1;
            dt.Rows.Add(dr);
            ViewState["currenttable"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();
            DropDownList ddl1 = (DropDownList)GridView1.Rows[0].Cells[1].FindControl("ddlfeelings");
            DropDownList ddl2 = (DropDownList)GridView1.Rows[0].Cells[2].FindControl("ddlno");
            DropDownList ddl3 = (DropDownList)GridView1.Rows[0].Cells[3].FindControl("ddlday");
            DropDownList ddl4 = (DropDownList)GridView1.Rows[0].Cells[4].FindControl("ddlspecifications");
            fildrop(ddl1);
            fildrop(ddl2);
            fildrop(ddl3);
                fildrop(ddl4);
        }
        protected void addnewrow()
        {
            if (ViewState["currenttable"] != null)
            {
                DataTable dtcurrenttable = (DataTable)ViewState["currenttable"];
                DataRow drCurrentRow = null;
                if (dtcurrenttable.Rows.Count > 0)
                {
                    drCurrentRow = dtcurrenttable.NewRow();
                    drCurrentRow["rowno"] = dtcurrenttable.Rows.Count + 1;
                    dtcurrenttable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtcurrenttable;

                    for (int i = 0; i < dtcurrenttable.Rows.Count - 1; i++)
                    {
                        DropDownList ddl1 = (DropDownList)GridView1.Rows[i].Cells[1].FindControl("ddlfeelings");
                        DropDownList ddl2 = (DropDownList)GridView1.Rows[i].Cells[2].FindControl("ddlno");
                        DropDownList ddl3 = (DropDownList)GridView1.Rows[i].Cells[3].FindControl("ddlday");
                        DropDownList ddl4 = (DropDownList)GridView1.Rows[i].Cells[4].FindControl("ddlspecifications");


                        dtcurrenttable.Rows[i]["col1"] = ddl1.SelectedItem.Text;
                        dtcurrenttable.Rows[i]["col2"] = ddl2.SelectedItem.Text;
                        dtcurrenttable.Rows[i]["col3"] = ddl3.SelectedItem.Text;
                        dtcurrenttable.Rows[i]["col4"] = ddl4.SelectedItem.Text;
                    }

                    GridView1.DataSource = dtcurrenttable;
                    GridView1.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }


            setpreviousdata();
        }
        protected void setpreviousdata()
        {
            int rowIndex = 0;
            if (ViewState["currenttable"] != null)
            {
                DataTable dt = (DataTable)ViewState["currenttable"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        DropDownList ddl1 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("ddlfeelings");
                        DropDownList ddl2 = (DropDownList)GridView1.Rows[rowIndex].Cells[2].FindControl("ddlno");
                        DropDownList ddl3 = (DropDownList)GridView1.Rows[rowIndex].Cells[3].FindControl("ddlday");
                        DropDownList ddl4 = (DropDownList)GridView1.Rows[rowIndex].Cells[3].FindControl("ddlspecifications");
                        fildrop(ddl1);
                        fildrop(ddl2);
                        fildrop(ddl3);
                        fildrop(ddl4);

                        if (i < dt.Rows.Count - 1)
                        {
                            ddl1.ClearSelection();
                            ddl1.Items.FindByText(dt.Rows[i]["col1"].ToString()).Selected = true;

                            ddl2.ClearSelection();
                            ddl2.Items.FindByText(dt.Rows[i]["col2"].ToString()).Selected = true;

                            ddl3.ClearSelection();
                            ddl3.Items.FindByText(dt.Rows[i]["col3"].ToString()).Selected = true;
                            ddl4.ClearSelection();
                            ddl4.Items.FindByText(dt.Rows[i]["col4"].ToString()).Selected = true;
                        }

                        rowIndex++;
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                setfirstrow();
            }
        }
     
        protected void btnadd_Click(object sender, EventArgs e)
        {
            addnewrow();
        }
    }
}
--------------aspx--------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="autorowgenaration.WebForm1" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 182px;
        }
        .style3
        {
            width: 130px;
        }
        .style4
        {
            width: 143px;
        }
        .style5
        {
            width: 174px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table id="tblfeel" class="style1">
        <tr>
            <td class="style2">
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                <Columns>
                <asp:BoundField DataField="rowno" HeaderText="sno" />
                <asp:TemplateField HeaderText="feelings">
                <ItemTemplate>
                <asp:DropDownList ID="ddlfeelings" runat="server">
                <asp:ListItem>i am feeling</asp:ListItem>
                </asp:DropDownList>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="no">
                <ItemTemplate>
                <asp:DropDownList ID="ddlno" runat="server">
                <asp:ListItem>--no--</asp:ListItem>
                </asp:DropDownList>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="day">
                <ItemTemplate>
                <asp:DropDownList ID="ddlday" runat="server">
                <asp:ListItem>Day</asp:ListItem>
                </asp:DropDownList>
                 </ItemTemplate>
                 </asp:TemplateField>
                 <asp:TemplateField HeaderText="specifications">
                 <ItemTemplate>
                 <asp:DropDownList ID="ddlspecifications" runat="server">
                 <asp:ListItem>Specification</asp:ListItem>
                 </asp:DropDownList>
                 </ItemTemplate>
               <FooterTemplate>
               <asp:Button ID="btnadd" runat="server" Text="Add new row" />
               </FooterTemplate>
                </asp:TemplateField>
                </Columns>
                </asp:GridView>
            </td>
            <td class="style3">
                &nbsp;</td>
            <td class="style4">
                &nbsp;</td>
            <td class="style5">
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
    </table>
    <asp:Button ID="btnadd" runat="server" onclick="btnadd_Click" Text="ADD" />
    </form>
</body>
</html>

Tuesday, June 16, 2015

changing theme dynamicaly in master page

To implement this first create new website in visual studio after that right click on your website and select Add New Item after that select Master page and click OK. Now master page added to your application. Now again right click on your website and select Add ASP.NET Folder under that selectTheme now App_Themes folder will add to your application. Now right click on App_Themes folder and create two new Asp.net folders and give names as “Blue” and “Red”. Now select Blue folder under that add one skin file and one css file same way add skin file and css file in Red folder also. Here we need to use Page_PreInit event in all the pages wherever we need to change themes dynamically for that reason instead of writing this same event in all the pages we need to create new class file and give name as ThemeClass and write following code.

Over all our structure of the application will be like this


---------------master page-----------------------------------

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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>

    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            height: 237px;
        }
        .style3
        {
            height: 237px;
            width: 46px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
        <table class="style1">
            <tr>
                <td align="center" colspan="2">
                    article</td>
            </tr>
            <tr>
                <td class="style3">
                </td>
                <td class="style2">
                    <asp:ContentPlaceHolder ID="head" runat="server">
                    </asp:ContentPlaceHolder>
                    <b>Click Button to change Theme</b><br />
<asp:Button ID="btnBlue" runat="server" Text="Blue" BackColor="#44BCED" Font-Bold="true"
                        onclick="btnBlue_Click" />
<asp:Button ID="btnRed" runat="server" Text="Red" BackColor="Red" Font-Bold="true"
                        onclick="btnRed_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;</td>
            </tr>
        </table>
     
    </div>
    </form>
</body>
</html>

-------------------------------------------------master page.cs----------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    public class ThemeClass: System.Web.UI.Page
    {
       
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnBlue_Click(object sender, EventArgs e)
    {

        Session["Theme"] = btnBlue.Text;
        Server.Transfer(Request.FilePath);
      
    }
    protected void btnRed_Click(object sender, EventArgs e)
    {
       Session["Theme"]=btnRed.Text;
       Server.Transfer(Request.FilePath);
    }
}
--------------------------------default.aspx-----------------------------------------
<%@ Page Title="" Theme="blue" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
 <asp:Panel ID="pnllogin" runat="server" Height="148px" 
        style="margin-left: 529px" BackColor="#33CCFF" BorderColor="#CC00CC" 
        BorderStyle="Solid" BorderWidth="5px" ForeColor="#0099CC" 
    Width="323px" >
        <br />
        <br />
        &nbsp;<asp:Label ID="lblname" runat="server" ForeColor="Blue" Text="NAME"></asp:Label>
        &nbsp;
        <asp:TextBox ID="name" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="lblpassword" runat="server" ForeColor="Blue" Text="Password"></asp:Label>
        <asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnlogin" runat="server" Height="26px" Text="LOG IN" 
            Width="63px" />
        &nbsp;<asp:Button ID="btnregister" runat="server" Text="REGISTER" />
    </asp:Panel>
    <asp:GridView ID="GridView1" runat="server" BorderColor="#CC0099" 
        BorderStyle="Solid" BorderWidth="5px" AutoGenerateColumns="False">
        <Columns>
           
            <asp:TemplateField HeaderText="Title">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("c_Articles_Name") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("c_Articles_Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Category">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" 
                        Text='<%# Bind("c_Articles_Details") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("c_Articles_Details") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Author">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" 
                        Text='<%# Bind("c_CAND_AUTHENTICATION_UserId") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" 
                        Text='<%# Bind("c_CAND_AUTHENTICATION_UserId") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="PostedDate">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("c_Articles_Date") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("c_Articles_Date") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
           
        </Columns>
    </asp:GridView>
</asp:Content>
-------------------------------------------------------default.aspx.cs----------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    
        protected void page_preInit(object sender, EventArgs e)
        {
            if (Session["Theme"] != null)
            {
                Page.Theme = Session["Theme"].ToString();
            }
        }
    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
-------------------------------stylesheet-----------------------------
body
{
font-size: 15pt;
color: #000000;
background-color: Red;
}
--------------------------------skinfile-------------------------------
<asp:Label runat="server"  Font-Bold="true" Font-Italic="true" />
<asp:Textbox runat="server"  BackColor="Orange" BorderColor="DarkCyan" BorderStyle="Dotted" BorderWidth="2" />

Sunday, May 31, 2015

update and delete gridview rows

code behind:
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;

namespace gridviewedit
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection _con = new SqlConnection("Data Source=db205.my-hosting-panel.com;Initial Catalog=goggery_sample;Persist Security Info=True;User ID=goggery_sample;Password=sample1.0");
         protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bind();
            }
        }
         protected void bind()
         {
             SqlCommand _cmd = new SqlCommand("select * from emp_nandu", _con);
             DataSet _ds = new DataSet();
             SqlDataAdapter _da = new SqlDataAdapter(_cmd);
             _da.Fill(_ds);
             GridView1.DataSource = _ds;
             GridView1.DataBind();
         }
   
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
            int EMP_ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            Label Lbl = (Label)row.FindControl("lblemp_id");
            TextBox txtename = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtename");
            TextBox txtmanager = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtmanager");
            TextBox txtdept = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtdept");
            TextBox txtsal = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtsal");
           
            GridView1.EditIndex = -1;
 0    
SqlCommand _cmd = new SqlCommand("update emp_nandu set ENAME='"+txtename.Text+"',MANAGER_ID='"+txtmanager.Text+"',DEPT='"+txtdept.Text+"', SAL='"+txtsal.Text+"' where EMP_ID="+EMP_ID+"", _con);
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
bind();
     

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            bind();

        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["EMP_ID"].ToString());
          //  string username = GridView1.DataKeys[e.RowIndex].Values["UserName"].ToString();
            _con.Open();
            SqlCommand _cmd = new SqlCommand("delete from emp_nandu where EMP_ID='"+id+"'", _con);
            _cmd.ExecuteNonQuery();
            _con.Close();
            bind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();

        }

     
    }
}
asp page code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="gridviewedit.WebForm1" %>

<!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 style="height: 257px; width: 627px">
    <form id="form1" runat="server">
    <div>
   
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EMP_ID"
        onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
        onrowupdating="GridView1_RowUpdating"
        Height="211px"
        Width="617px" >
        <Columns>
       
            <asp:TemplateField HeaderText="EMP_ID">
                <EditItemTemplate>
                    <asp:TextBox ID="txtemp_id" runat="server" Text='<%# Eval("EMP_ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblemp_id" runat="server" Text='<%# Eval("EMP_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ENAME">
                <EditItemTemplate>
                    <asp:TextBox ID="txtename" runat="server" Text='<%# Eval("ENAME") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblename" runat="server" Text='<%# Eval("ENAME") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="MANAGER">
                <EditItemTemplate>
                    <asp:TextBox ID="txtmanager" runat="server" Text='<%# Eval("MANAGER_ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblmanager" runat="server" Text='<%# Eval("MANAGER_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="DEPT">
                <EditItemTemplate>
                    <asp:TextBox ID="txtdept" runat="server" Text='<%# Eval("DEPT") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lbltext" runat="server" Text='<%# Eval("DEPT") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="SAL">
                <EditItemTemplate>
                    <asp:TextBox ID="txtsal" runat="server" Text='<%# Eval("SAL") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblsal" runat="server" Text='<%# Eval("SAL") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:CommandField ShowCancelButton="true" />
            <asp:CommandField ShowEditButton="true" />
            <asp:CommandField ShowDeleteButton="true" />
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>

Thursday, May 14, 2015

logfile in c#

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;
using System.IO;

namespace logfile
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection _con = new SqlConnection("Data Source=db205.my-hosting-panel.com;Initial Catalog=goggery_sample;User ID=goggery_sample;Password=sample1.0");
        protected void Page_Load(object sender, EventArgs e)
        {

        }
     

        public void LogFile(string sExceptionName, string sEventName, string sFormName)
        {

            StreamWriter log;

            if (!File.Exists("logfile.txt"))
            {

                log = new StreamWriter("E:\\nandu\\logfile.txt");

            }

            else
            {

                log = File.AppendText("E:\\nandu\\logfile.txt");

            }

            // Write to the file:

            log.WriteLine("Data Time:" + DateTime.Now);

            log.WriteLine("Exception Name:" + sExceptionName);

            log.WriteLine("Event Name:" + sEventName);

            //log.WriteLine("Control Name:" + sControlName);

            //log.WriteLine("Error Line No.:" + nErrorLineNo);

            log.WriteLine("Form Name:" + sFormName);

            // Close the stream:

            log.Close();

        }
       

        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommand _cmd = new SqlCommand("insert into log_nandu values('" + txtname.Text + "','" + txtcourse.Text + "','" + txtfee.Text + "')", _con);
                _con.Open();
                _cmd.ExecuteNonQuery();
                _con.Close();
            }
            catch (Exception exe)
            {

                //call LogFile method and pass argument as Exception message, event name, control         name, error line number, current form name

                LogFile(exe.Message, exe.ToString(),this.Page.ToString());

            }
        }


    }
}

Monday, March 9, 2015

interface c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace inter
{

    public interface operations
    {

        void operation();
        int add();
        int sub();
        //int mult();
    }
    public class math : operations
    {
        private int x1;
        private int y1;

     
        public math(int x, int y)
        {
            x1 = x;
            y1 = y;

        }
        public int add()
        {
            return x1 + y1;
        }
        public int sub()
        {
            return x1 - y1;
        }
        public void operation()
        {
            Console.WriteLine("x1: {0}", x1);
            Console.WriteLine("y1:{0}", y1);
            Console.WriteLine("add:{0}", add());
            Console.WriteLine("sub:{0}", sub());
        }
    }
        public class math2 : operations
        {
            private int a;
            private int b;

            public math2(int c, int d)
            {
                a = c;
                b = d;
            }
            public int mult()
            {
                return a * b;
            }
            public void operation()
            {
                Console.WriteLine("a: {0}", a);
                Console.WriteLine("b:{0}", b);
                Console.WriteLine("add:{0}", mult());
               
            }
        }
   
    class Tester
    {
        static void Main(string[] args)
        {
            math madd = new math(20, 30);
            math2 m2= new math2(10,30);
            madd.operation();
            m2.operation();
            Console.ReadKey();
        }
    }
}



operator over loading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace oprovr
{
    class program
    {
     
       
       
            public int fun(int a, int b)
            {
               
                return(a+b);
            }
            public int fun(int a, int b, int c)
            {
                return(a+b+c);
            }
            public string fun(string a, string b)
            {
                return(a+b);
            }
   
        static void Main(string[] args)
        {
            //Console.WriteLine("enter values");
           //int a=Convert.ToInt32(Console.ReadLine());
           //int b=Convert.ToInt32(Console.ReadLine());
           program f= new program();
            int c=f.fun(3,5);
            int b=f.fun(1,2,3);
            string s = f.fun("over", "loading");
            Console.WriteLine("two sum" +c);
            Console.WriteLine("three sum" +b);
            Console.WriteLine(s);


            Console.ReadKey();
        }
       

    }
}

polyndrom using for loop c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace polyn
{
    class Program
    {
        static void Main(string[] args)
        {
            string s,revs="";
            Console.WriteLine("enter string");
            s = Console.ReadLine();
            for (int i = s.Length-1 ; i>= 0; i--)
            {
                revs += s[i].ToString();
            }


            if (revs == s)
            {
                Console.WriteLine("given string is polyndrum \ngiven string is {0}\nrevs string is {1}", s, revs);
            }
            else
            {
                Console.WriteLine("given string is not polyndrum \ngiven string is {0}\nrevs string is {1}", s, revs);
            }
            Console.ReadKey();

        }
    }
}

polyndrom using while c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace polyn_while
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, rev = 0, rem,temp=0;
            Console.WriteLine("enter a no");
            num = Convert.ToInt32(Console.ReadLine());
            temp = num;
            while (num > 0)
            {
                rem = num % 10;
                rev= rev * 10 + rem;
                num = num / 10;
            }
            if (rev== temp)
            {
                Console.WriteLine("given no is polyn:{0}",rev);
            }
            else
            {
                Console.WriteLine("given no is not a polyn:{0}", rev);

            }
            Console.ReadKey();
        }
    }
}

prime number c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace prime
{
    class Program
    {
        static void Main(string[] args)
        {
                 bool isPrime = true;
            Console.WriteLine("Prime Numbers : ");
            for (int i = 2; i <= 10; i++)
            {
                for (int j = 2; j <= 10; j++)
                {

                    if (i != j && i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }

                }
                if (isPrime)
                {
                    Console.Write("\t" +i);
                }
                isPrime = true;
            }
            Console.ReadKey();
        }
    }
}
        

reverse sentence c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace revarse_sentence
{
    class Program
    {
        static void Main(string[] args)

        {

         
    string str = Console.ReadLine();
            string strrev = "";
           
            foreach (var word in str.Split(' ') )
            {
                string temp = "";
                foreach (var ch in word.ToCharArray())
                {
                    temp = ch + temp;
                }
                strrev = strrev + temp + " ";
            }
            Console.WriteLine(strrev);
            Console.ReadLine();
        }
    }
}

reverse string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace reverse_string
{
    class Program
    {
        static void Main(string[] args)
        {

            string str, revstr = "";
            int length;
            Console.WriteLine("enter string");
            str = Console.ReadLine();
                length= str.Length-1;
            while(length>=0)
            {
                revstr = revstr + str[length];
                length--;
            }
                Console.WriteLine("rev string is {0}", revstr);
                Console.ReadKey();
        }
    }
}

c# string functions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace stringfun
{
    class Program
    {
        static void Main(string[] args)
        {
                string firstname;
            string lastname;
         
         
            firstname = "nanda kishore";
            lastname = "kishore";


  Console.WriteLine(firstname.Clone());
// Make String Clone
            Console.WriteLine(firstname.CompareTo(lastname));
//Compare two string value and returns 0 for true and
//1 for false;

 Console.WriteLine(firstname.Contains("da")); //Check whether specified value exists or not in string

  Console.WriteLine(firstname.EndsWith("a")); //Check whether specified value is the last character of string
            Console.WriteLine(firstname.Equals(lastname));
//Compare two string and returns true and false


  Console.WriteLine("hash codse",firstname.GetHashCode());
//Returns HashCode of String

  Console.WriteLine("type of stiring",
      firstname.GetType());
//Returns type of string

  Console.WriteLine(firstname.GetTypeCode());
//Returns type of string

  Console.WriteLine(firstname.IndexOf("e")); /*Returns the first index position of specified value
the first index position of specified value*/

  Console.WriteLine(firstname.ToLower());
//Covert string into lower case

  Console.WriteLine(firstname.ToUpper());
//Convert string into Upper case

  Console.WriteLine(firstname.Insert(0, "Hello")); //Insert substring into string

  Console.WriteLine(firstname.IsNormalized());
/*Check Whether string is in Unicode normalization
from C*/


   Console.WriteLine(firstname.LastIndexOf("e")); //Returns the last index position of specified value

 Console.WriteLine(firstname.Length);
//Returns the Length of String

 Console.WriteLine(firstname.Remove(5));
//Deletes all the characters from begining to specified index.

 Console.WriteLine(firstname.Replace('e','i')); // Replace the character

  string[] split = firstname.Split(new char[] { 'i' }); //Split the string based on specified value


            Console.WriteLine(split[0]);
            Console.WriteLine(split[1]);
          //  Console.WriteLine(split[2]);

  Console.WriteLine(firstname.StartsWith("S")); //Check wheter first character of string is same as specified value

  Console.WriteLine(firstname.Substring(2,5));
//Returns substring

  Console.WriteLine(firstname.ToCharArray());
//Converts an string into char array.

  Console.WriteLine(firstname.Trim());
/*It removes starting and ending white spaces from
string.*/
  Console.ReadKey();
         
        }
    }
}
     
 

word count c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace word_count
{
    class Program
    {
        static void Main(string[] args)
        {
           
            string str= Console.ReadLine();
              int last = str.Length-1;

  int count = 0;
  for (int i = 0; i <= last; i++)
  {
      if (char.IsLetterOrDigit(str[i]) &&
           ((i <= last) || char.IsWhiteSpace(str[i + 1]) || char.IsPunctuation(str[i + 1])))
      {
          count++;
      }
  }
  Console.WriteLine(count);
  Console.ReadLine();
       
           
        }
    }
}

multi level inheritence using interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace inter
{

     interface operations
    {
     
        void operation();
        int add();
         int sub();
       
    }
    public class math1: operations
    {
        public int x=10;
        public int y=20;
      public int add()
        {
            return x + y;
        }
      public int sub()
      {
          return x - y;
      }
       
        public void operation()
        {
            Console.WriteLine("x1: {0}", x);
            Console.WriteLine("y1:{0}", y);
            Console.WriteLine("base add:{0}", add());
           
        }
    }
    public class math2: math1,operations
    {
        public int add()
        {
            return x + y;
        }
       
      public int sub()
        {
            return x*y;
        }
      public void operation()
      {
          Console.WriteLine("\nmath 2 sub :{0}", sub());
          Console.WriteLine("\n math2 add :{0}",add());
      }
     
    }

    public class math3 : math1, operations
    {

        //public int a=10;
        //public int b=50;
       
        public int add()
        {
            return x+y;
        }
        public int sub()
        {
            return x-y;
        }
        public void operation()
        {
            Console.WriteLine("a: {0}", x);
            Console.WriteLine("b:{0}", y);
            Console.WriteLine("\nmath3 add:{0}", add());
            Console.WriteLine("math3 sub:{0}", sub());
        }
    }

    class Tester
    {
        static void Main(string[] args)
        {
        //math1 m1 = new math1();
        math2 m2 = new math2();
            math3 m3 = new math3();
            //m1.operation();
           
            m2.operation();
            m3.operation();
            Console.ReadKey();
        }
    }
}



Tuesday, March 3, 2015

OOPs interface vs abstract class

InterfaceAbstract class
Interface support multiple inheritanceAbstract class does not support multiple inheritance
Interface does'n Contains Data MemberAbstract class contains Data Member
Interface does'n contains CunstructorsAbstract class contains Cunstructors
An interface Contains only incomplete member (signature of member)An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as publicAn abstract class can contain access modifiersfor the subs, functions, properties
Member of interface can not be StaticOnly Complete Member of abstract class can be Static

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
FeatureInterfaceAbstract class
Multiple inheritanceA class may inherit several interfaces.A class may inherit only one abstract class.
Default implementationAn interface cannot provide any code, just the signature.An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Core VS PeripheralInterfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.An abstract class defines the core identity of a class and there it is used for objects of the same type.
HomogeneityIf various implementations only share method signatures then it is better to use Interfaces.If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
SpeedRequires more time to find the actual method in the corresponding classes.Fast
Adding functionality (Versioning)If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined

Tuesday, February 10, 2015

DISPLYING EMP DETAILS MONTH WISE WITH MONTH NAME



select datepart (month, HIRE_DATE) 'month', count(*) 'no of employees'
from EMPLOYEE_NANDU group by datepart(month,HIRE_DATE)

-----DISPLYING EMP DETAILS MONTH WISE WITH MONTH NAME---------

SELECT  MONTH=DATENAME(MM,HIRE_DATE) , count(*) 'no of employees'
FROM EMPLOYEE_NANDU GROUP BY DATENAME(MM,HIRE_DATE)

----DISPLAYING NAMES MONTH WISE AND NO OF EMPS AND NAMES--------------

DISPLAYING NAMES MONTH WISE AND NO OF EMPLOYEES AND NAMES

SELECT DATENAME(MM,E1.HIRE_DATE)'MONTH' ,COUNT(*) 'NO OF EMPLOYEES', STUFF((SELECT ',' + E2.FIRST_NAME
FROM
 EMPLOYEE_NANDU AS E2
WHERE DATENAME(MM,E1.HIRE_DATE)=DATENAME(MM,E2.HIRE_DATE)
 FOR XML PATH('')), 1,1,'')AS ENAME
FROM EMPLOYEE_NANDU AS E1 WHERE HIRE_DATE IS NOT NULL GROUP BY DATENAME(MM,HIRE_DATE)

Sunday, February 8, 2015

Word Count in a Sentence




namespace word_count
{
    class Program
    {
        static void Main(string[] args)
        {

            string str = Console.ReadLine();
              int last = str.Length-1;

  int count = 0;
  for (int i = 0; i <= last; i++)
  {
    if ( char.IsLetterOrDigit(str[i]) &&
         ((i==last) || char.IsWhiteSpace(str[i+1]) || char.IsPunctuation(str[i+1])) )
      count++;
  }

  Console.WriteLine(count);
  Console.ReadLine();
        }
    }
}


how to reverse the sentence witout changing tha words position




ex: hi this is string
rev: ih siht si gnirts






    static void Main(string[] args)
        {
            string str = Console.ReadLine();
            string strrev = "";

            foreach (var word in str.Split(' '))
            {
                string temp = "";
                foreach (var ch in word.ToCharArray())
                {
                    temp = ch + temp;
                }
                strrev = strrev + temp + " ";
            }
            Console.WriteLine(strrev);
            Console.ReadLine();
        }

Thursday, February 5, 2015

Deleting related rows in two tables

             --DELETING RELATED COLUMNS IN TWO TABLES----

CREATE TABLE DEP_NANDU(
DEPT_ID INT NOT NULL,
DNAME VARCHAR(20)  NOT NULL,
LOCATION VARCHAR(10) NOT NULL,
CONSTRAINT PK_DEP_NANDU PRIMARY KEY (DEPT_ID))

SELECT * FROM DEPT_NANDU

INSERT INTO DEPT_NANDU VALUES(80, 'TRANSPORT', 'DUBAI')

CREATE TABLE EMPLY_NANDU(EMP_ID INT NOT NULL,
ENAME VARCHAR(20) NOT NULL,
SAL INT,
DEPT_ID INT NOT NULL,
DNAME VARCHAR(15) NOT NULL,


SELECT * FROM EMPLY_NANDU

INSERT INTO DEP_NANDU SELECT * FROM DEPT_NANDU
DELETE * FROM DEP_NANDU


                                     ------ADDING CONSTRAINT-----

ALTER TABLE TABLENAME ADD CONSTRAINT PK_TABLENAME PK(CLMN NAME)

ALTER TABLE EMPLY_NANDU ADD CONSTRAINT PK_EMPLY_NANDU PRIMARY KEY(DEPT_ID)

 INSERT INTO EMPLY_NANDU VALUES(106,'SFSG',5000,90,'SALES')

SELECT * FROM DEP_NANDU
SELECT * FROM EMPLY_NANDU
 ALTER TABLE EMPLY_NANDU DROP CONSTRAINT PK_EMPLY_NANDU

                                --ADDING ON DELETE CONSTRAINT----



ALTER TABLE EMPLY_NANDU  ADD CONSTRAINT FK_DEP_NANDU
 FOREIGN KEY(DEPT_ID) REFERENCES DEP_NANDU(DEPT_ID)
ON UPDATE CASCADE
ON DELETE CASCADE


DELETE DEP_NANDU WHERE DEPT_ID=70