How to use if else inside the Repeater control using C#?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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">
    <div>
   
        <asp:DataList ID="DataList1" runat="server">
        </asp:DataList>
   
    </div>
    <asp:Repeater ID="Repeater1" runat="server"
        onitemcommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" CommandName="cmd" runat="server" Text='<%#Eval("name") %>'>LinkButton</asp:LinkButton>
    </ItemTemplate>
    </asp:Repeater>
    </form>
</body>
</html>
..............................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"server=COMTECH-PC\SQLEXPRESS;database=ShriGaneshayNamah;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str,con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="cmd")
        {
            LinkButton lnk = (LinkButton)e.Item.FindControl("LinkButton1");
            string name = lnk.Text;
            if(name=="kul")
            {
                Response.Redirect("https://www.google.co.in/?gfe_rd=cr&ei=vlqFVr78G6fR8AfnlJ_wAQ&gws_rd=ssl");
            }
            else if(name=="raj")
            {
                Response.Redirect("https://www.facebook.com/");
            }
        }
    }
}
Share:

How to create Repeater paging in Asp.net using 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.Text;
using System.Data.SqlClient;
using System.Globalization;

public partial class ifrmenquire_kappl_awards : System.Web.UI.Page
{
    int totalCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
         
        }

        try
        {
            DataSet ds = new DataSet();
            String sql = "sp_get_award";

            SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
            adapter.Fill(ds);
            totalCount = ds.Tables[0].Rows.Count;
            bindData();
       
        }
        catch(Exception ex)
        {
        }
     
    }
    public void bindData()
    {
        try
        {
            DataSet ds = new DataSet();
            String sql = "sp_get_award";
            int val = Convert.ToInt16(txtHidden.Value);
            if (val <= 0)
                val = 0;

            SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
            adapter.Fill(ds, val, 9, "blogs_Posts");
            rptritems.DataSource = ds;
            rptritems.DataBind();

            if (val <= 0)
            {
                lnkBtnPrev.Visible = false;
                lnkBtnNext.Visible = true;
            }

            if (val >= 3)
            {
                lnkBtnPrev.Visible = true;
                lnkBtnNext.Visible = true;
            }

            if ((val + 3) >= totalCount)
            {
                lnkBtnNext.Visible = false;
            }
        }
        catch(Exception ex)
        {
        }
    }
    protected void lnkBtnPrev_Click(object sender, EventArgs e)
    {
        try
        {
            txtHidden.Value = Convert.ToString(Convert.ToInt16(txtHidden.Value) - 6);
            bindData();
        }
        catch (Exception ex)
        {
        }
    }
    protected void lnkBtnNext_Click(object sender, EventArgs e)
    {
        try
        {
            txtHidden.Value = Convert.ToString(Convert.ToInt16(txtHidden.Value) + 6);
            bindData();
        }
        catch(Exception ex)
        {
        }
     
    }
    private void LoadDataForAwards()
    {
        try
        {
            BlogsDAL dal = new BlogsDAL();
            DataTable dt = dal.LoadDataForAwardsPost(Util.GetSourceWebsite());
            rptritems.DataSource = dt;
            rptritems.DataBind();
        }
        catch(Exception ex)
        {
            throw;
        }
       
    }


    protected void rptritems_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try{
            if (e.CommandName == "cmd")
            {
                string str = "sp_get_award";
                SqlDataAdapter da = new SqlDataAdapter(str, Util.GetSourceWebsite());
                DataSet ds = new DataSet();
                da.Fill(ds);
                string name = ds.Tables[0].Rows[0]["Author"].ToString();
                if (name == "Abhilash")
                {
               
                    Response.Redirect("http://www.whyayurveda.org/author/abhilash-k.r.aspx");
                }
                else if (name == "Gita")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/gita-ramesh.aspx");
                }
                else if (name == "Abishek")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/abishek-k.r.aspx");
                }
                else if (name == "reeta-bhattacharjee")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/reeta-bhattacharjee.aspx");
                }
                else if (name == "ramesh")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/ramesh-k.v.aspx");
                }
            }
        }
        catch(Exception ex)
        {
        }
    }
    protected void rptritems_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataSet ds = new DataSet();
                String sql = "sp_get_award";
                DateTime date;
                SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
                adapter.Fill(ds);
                string getdate = ds.Tables[0].Rows[0]["post_AddedDate"].ToString();
               
                date = Convert.ToDateTime(getdate);

                Label lblAnswer = e.Item.FindControl("Label1") as Label;
                lblAnswer.Text = date.ToString("ddd d MMM yyyy", CultureInfo.CreateSpecificCulture("en-US"));

               
            }
        }
        catch(Exception ex)
        {
        }
    }
}
................................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ifrmenquire_kappl_awards.aspx.cs" Inherits="ifrmenquire_kappl_awards" %>

<!DOCTYPE html>
<html lang="en-US">
<head runat="server">
    <title></title>
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="css/kappl-awards.css" />

    <script src="css/jQuery1.9.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server" class="pad10awd">
    <div id="divTop5" runat="server">
                </div>
    <div class="blogwhy">
        <ul class="whyayurveda">
            <asp:Repeater ID="rptritems" runat="server" 
                onitemcommand="rptritems_ItemCommand" onitemdatabound="rptritems_ItemDataBound" 
                >
                <ItemTemplate>
                    <li class="blog<%# DataBinder.Eval(Container.DataItem, "post_kid")%>">
                        <div class="whytitle">
                            <a onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);" class="posttitle">
                                <%# DataBinder.Eval(Container.DataItem, "post_title")%></a>
                        </div>
                        <div class="whydescription">
                            <div class="postsummary">
                                <%# DataBinder.Eval(Container.DataItem, "post_summary")%>
                            </div>
                            <div class="hidden postcontent">
                                <%# DataBinder.Eval(Container.DataItem, "post_title")%>
                            </div>
                            <div class="hidden mainurulwhy">
                                <%# DataBinder.Eval(Container.DataItem, "post_mainimagename")%>
                            </div>
                        </div>
                        <div class="whypic">
                            <a><span>
                                <img class="img1" src=" <%# DataBinder.Eval(Container.DataItem, "post_MainImageName")%>" />
                                <span class="viewdtl" onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);">
                                </span></a>
                        </div>
                        <div class="whyposted">
                            <p>
                                Posted By 
                                <a target="_blank" href="<%# DataBinder.Eval(Container.DataItem, "author")%>">
                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="cmd" Text='<%# DataBinder.Eval(Container.DataItem, "author")%>'>LinkButton</asp:LinkButton>
                                    
                                    
                        <%-- <%# DataBinder.Eval(Container.DataItem, "author")%>--%>

                                  </a>
                                  posted on  
                                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                                  
<%--                                 <%#Eval("post_AddedDate", "{0:D}")%>
--%>                                at
                                <br />
                                <%#Eval("post_AddedDate", "{0:t}")%>
                            </p>
                        </div>
                        <div class="learnmore">
                            <a onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);">Learn
                                More</a>
                        </div>
                    </li>
                </ItemTemplate>
            </asp:Repeater>
        </ul>
        <div class="paging">
            <input id="txtHidden" style="width: 28px" type="hidden" value="0" runat="server" /><hr>
            <asp:LinkButton ID="lnkBtnPrev" runat="server" Font-Underline="False" OnClick="lnkBtnPrev_Click"
                Font-Bold="True"><span class="prevpanel">← Prev</span></asp:LinkButton>
            &nbsp;&nbsp;
            <asp:LinkButton ID="lnkBtnNext" runat="server" Font-Underline="False" OnClick="lnkBtnNext_Click"
                Font-Bold="True"><span class="nextpanel">Next →</asp:LinkButton>
        </div>
    </div>
    <div class="blogwhyfull hideme">
        <div class="basecent">
            <div class="close-dtl">
                <a onclick="$('.blogwhyfull').hide();">x</a>
            </div>
            <ul class="whyayurvedapop">
                <li>
                    <div class="whytitle1 cnt">
                    </div>
                    <div class="whyposted1 cnt">
                    </div>
                    <div class="whydescription1 cnt sammary">
                    </div>
                    <div class="whypic1">
                        <img class="img2" alt="blog" />
                    </div>
                    <div class="whydescription1 cnt maindesc">
                    </div>
                    <p>
                        <strong>Courtesy:</strong> <a href="http://www.whyayurveda.org/products/2014/09/22/ayurveda-for-hair-diseases.aspx">Whyayurveda</a>
                    </p>
                    <div class="arrows-nex-prev pop">
                  


                    <a  href="http://www.kairaliproducts.in/enqurie-now"><span class="prevpanel">Enquire Now</span>
                    </a>
                    <a  href="http://www.kairaliproducts.in/online-consultation"><span class="nextpanel">
                            Free Online Consultation</span> </a>
                    </div>
                </li>
            </ul>
        </div>
    </div>
    </form>

    <script language="javascript">
        function blogshow(id) {
            var options = {};
            $(".cnt").empty();
            $(".whytitle1").html($(".blog" + id).find('.posttitle').html());
            $(".sammary").html($(".blog" + id).find('.postsummary').html());
            $(".maindesc").html($(".blog" + id).find('.postcontent').html());
            $(".whyposted1").html($(".blog" + id).find('.whyposted').html());
            $(".img2").attr('src', $(".blog" + id).find('.img1').attr('src'));
            $("#alinkaway").attr('href', $(".blog" + id).find('.mainurulwhy').html());
            $(".blogwhyfull").show();
        }
        $(document).ready(function() {
            if (getParameterByName('id') > 0) {
                blogshow(getParameterByName('id'));
            }
        });
        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    </script>

</body>
</html>

Share:

Multi-Threading Program

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

namespace MultiTheadingAbort  
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread th = new Thread(writey);
            if (th.IsAlive)
            {
                th.Start();
                th.Abort();
            }
            for (int i = 0; i <= 10;i++ )
            {
                Console.WriteLine("hello");
            }
            Console.Read();
        }

        private static void writey()
        {
            for (int i = 0; i <= 9;i++ )
            {
                Console.WriteLine("kul");
            }
        }

    }
}

Share:

Threading Program

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

namespace mThreading
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread th = new Thread(writey);
            th.Start();
            for (int i = 0; i <= 10;i++ )
            {
                Console.WriteLine("hello");
            }
            Console.Read();
        }
        private static void writey()
        {
            for (int i = 0; i <= 9;i++ )
            {
                Console.WriteLine("world");
            }
        }
    }
}

Share:

What is Copy Constructor in C#? Example.

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

namespace CopyConstructor
{
    class Program
    {
        static void Main(string[] args)
        {
            Test T = new Test(10,20);
            T.Print();
            Console.Read();
        }
    }
    class Test

    {
        int A, B;
        public Test(int X,int Y)
        {
            A = X;
            B = Y;
        }
        public Test(Test T)
        {
           A = T.A;
           B = T.B;
        }
        public void Print()
        {
            Console.Write("A={0} and B={1}",A,B);
        }
 
    }
}

Share:

Parameterized Constructor

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

namespace ParameterizedConstructorExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Test T = new Test(10,20);
            T.Print();
            Console.Read();
        }
    }
    class Test
    {
        int A, B;
        public Test(int X, int Y)
        {
            A = X;
            B = Y;
        }
        public void Print()
        {
            Console.Write("A ={0} and B={1}",A,B);
        }
    }
}

Share:

How to find distinct element from multiple time's coming elements in the Array in C#

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

namespace FromMultipleElementsFindDistinctEach
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] ar = new int [] {1,1,1,2,2,2,2,2,3,4,4};
            var distinct = new HashSet<int>(ar);
            foreach (int i in distinct)
            {
                Console.Write(i+",");
            }
            Console.Read();
        }
    }
}

Share:

User valid or none valid procedure in SQL Server

create database zz
-create table
create table users (id int identity(1,1),username varchar(50),password
varchar(50))
--insert values in table
insert into users values('kul',123)
--create procedure
create proc getoutput
(
@UserName varchar(50),
@password varchar(50),
@UName varchar(50) OUTPUT,
@Pword varchar(50) OUTPUT
)
as
Begin
IF EXISTS(Select * FROM users WHERE UserName = @UserName AND Password = @password)
Begin
set @UName=@UserName
set @Pword=@password
end
else
begin
print 'You are not a valid user.'
end
End
--call procedure
declare @UsName varchar(50);
declare @pass varchar(50);
exec getoutput 'kul','1223' ,@UName=@UsName output,@Pword=@pass output
print @UsName
print @pass

        
Share:

How to get Textbox value in XML format and pass as a parameter using Asp.Net C#

       XmlDocument xmldoc=new XmlDocument();
        XmlElement emp_name = xmldoc.CreateElement(TextBox1.Text);
        string name= emp_name.Name;
        XmlElement emp_salary = xmldoc.CreateElement(TextBox2.Text);
        decimal salary = Convert.ToDecimal(emp_salary.Name);
        string str = "insert into emp values('"+name+"',"+salary+")";
        SqlCommand cmd = new SqlCommand(str,con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        BindGrid();
        Response.Write("<script>alert('Successfully saved !')</script>");
        TextBox1.Text = string.Empty;
        TextBox2.Text = string.Empty;
Share:

How to create stored procedure for Country, State, City for saving in SQL database?

Create database USERS
USE USERS

Create table TblCountry(CId int identity(1,1) primary key,Country varchar(50))
Create table TblState(SId int identity(1,1) primary key,FK_CountryId int references TblCountry(CId),State varchar(50))
Create table TblCity(CityId int identity(1,1) primary key,FK_StateId int references TblState(SId),FK_CountryId int,City varchar(50))

create proc abc
(
@country varchar(100),
@state varchar(100),
@city varchar(200)
)
as
begin
if not exists(select * from TblCountry where country=@country)
begin
insert into TblCountry(country) values(@country)
end
declare @countryid int;
select @countryid=CId from TblCountry where country=@country
if not exists(select * from TblState where State=@state)
begin
insert into TblState(FK_CountryId,state) values(@countryid,@state)
end

declare @stateid int;
select @stateid=SId from TblState where state=@state
if not exists(select * from TblCity where city=@city)
begin
insert into TblCity(FK_StateId,FK_CountryId,city)
values(@stateid,@countryid,@city)
end

end


select * from TblCountry
select * from TblState
select * from TblCity

execute dbo.abc 'America','LansAngile','Gaziabad'

Share:

Javascript Validation Form

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <%--this code for disable cut copy paste but enter number by key--%>
    <script language="javascript">
        function whichButton(event) {
            if (event.button == 2)//RIGHT CLICK
            {
                alert("Not Allow Right Click!");
            }

        }
        function noCTRL(e) {
            var code = (document.all) ? event.keyCode : e.which;

            var msg = "Sorry, this functionality is disabled.";
            if (parseInt(code) == 17) //CTRL
            {
                alert(msg);
                window.event.returnValue = false;
            }
        }
    </script>
    <%--this code for only numeric and strengh completed check--%>
    <script type="text/javascript">
        function ValidNumeric() {
            var p = document.getElementById('<%=txtpin.ClientID %>').value;
            var charCode = (event.which) ? event.which : event.keyCode;
            if (charCode >= 48 && charCode <= 57) {
                return true;
            }
            else if (p < 5) {
                alert('Only numeric number allow !');
                return false;
            }
            else {
                alert('Pin strengh has completed !');
                return false;
            }
        }
    </script>
    <script language="javascript" type="text/javascript">
        function validation() {
            var mobile = document.getElementById('<%=txtmbl.ClientID %>').value;
            var Email = document.getElementById('<%=txtmail.ClientID %>').value;
            var WebUrl = document.getElementById('<%=txturl.ClientID %>').value;
            var p = document.getElementById('<%=txtpin.ClientID %>').value;


            if (p == "") {
                alert("Enter Your Pin");
                document.getElementById("<%=txtpin.ClientID%>").focus();
                return false;
            }


            //            var digits = "0123456789";
            //            var temp;
            //            for (var i = 0; i < document.getElementById("<%=txtpin.ClientID %>").value.length; i++) {
            //                temp = document.getElementById("<%=txtpin.ClientID%>").value.substring(i, i + 1);
            //                if (digits.indexOf(temp) == -1) {
            //                    alert("Please enter correct pin code");
            //                    document.getElementById("<%=txtpin.ClientID%>").focus();
            //                    return false;
            //                }
            //            }

            if (WebUrl == "") {
                alert("Enter Your URL");
                document.getElementById("<%=txturl.ClientID %>").focus();
                return false;
            }
            var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
            var matchURL = WebUrl.match(Url);
            if (matchURL == null) {
                alert("Web URL does not look valid");
                document.getElementById("<%=txturl.ClientID %>").focus();
                return false;
            }

            if (Email == "") {
                alert("Enter Your Email");
                document.getElementById("<%=txtmail.ClientID%>").focus();
                return false;
            }
            var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
            var EmailmatchArray = Email.match(emailPat);
            if (EmailmatchArray == null) {
                alert("Your email must be this format eg. k@gmail.com !");
                document.getElementById("<%=txtmail.ClientID%>").focus();
                return false;
            }
            if (mobile == "") {
                alert("Enter Your Mobile Number !");
                document.getElementById("<%=txtmbl.ClientID%>").focus();
                return false;
            }
            var phoneno = /^\d{10}$/
            var EmailmatchArray = mobile.match(phoneno);
            if (EmailmatchArray == null) {
                alert("Number must be 10 digit !");
                document.getElementById("<%=txtmbl.ClientID%>").focus();
                return false;
            }

            if (document.getElementById('<%=txtname.ClientID%>').value == "") {
                alert('First Name must be required !');
                document.getElementById('<%=txtname.ClientID%>').focus();
                return false;
            }
            if (document.getElementById("<%=txtlname.ClientID%>").value == "") {
                alert('Last Name must be required !');
                document.getElementById("<%=txtlname.ClientID%>").focus();
                return false;
            }
            if (!document.getElementById('<%=rdomale.ClientID%>').checked && !document.getElementById('<%=rdofemale.ClientID%>').checked) {
                alert("Gender must be required !");
                document.getElementById('<%=rdomale.ClientID%>').focus();
                return false;
            }
            var atLeast = 1
            var CHK = document.getElementById('<%=CheckBoxList1.ClientID%>');
            var checkbox = CHK.getElementsByTagName("input");
            var counter = 0;
            for (var i = 0; i < checkbox.length; i++) {
                if (checkbox[i].checked) {
                    counter++;
                }
            }
            if (atLeast > counter) {
                alert('Please select one hobbies !');

                document.getElementById('<%=CheckBoxList1.ClientID%>').focus();
                return false;

            }

            var result = document.getElementById('<%=ddlEducation.ClientID%>').value.toString();
            if (result == "0") {
                alert('Please select a streem !');
                document.getElementById('<%=ddlEducation.ClientID%>').focus();
                return false;

            }
        }

    </script>
    <%--var ddltrader = document.getElementById('<%=ddltradername.ClientID%>');
            var ddlproductype1 = ddltrader.options[ddltrader.selectedIndex].value;--%>
    <style type="text/css">
        .style1
        {
            width: 50%;
            background-color: #FFCC99;
        }
        .style3
        {
            width: 68px;
        }
    </style>
</head>
<body>
    <form runat="server" id="form1">
    <table align="center" class="style1">
        <tr>
            <td class="style3">
                Pin
            </td>
            <td>
                <asp:TextBox ID="txtpin" runat="server" MaxLength="5" onMouseDown="whichButton(event)"
                    onKeyDown="return noCTRL(event)" onkeypress="return ValidNumeric()"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Url
            </td>
            <td>
                <asp:TextBox ID="txturl" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Email
            </td>
            <td>
                <asp:TextBox ID="txtmail" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Mobile
            </td>
            <td>
                <asp:TextBox ID="txtmbl" MaxLength="10" onkeypress="return ValidNumeric()" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <tr>
                <td class="style3">
                    First Name
                </td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Last Name
                </td>
                <td>
                    <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Gender
                </td>
                <td>
                    <asp:RadioButton ID="rdomale" runat="server" GroupName="k" name="gender" Text="Male" />
                    <asp:RadioButton ID="rdofemale" runat="server" GroupName="k" name="gender" Text="Female" />
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Hobbies
                </td>
                <td>
                    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
                        <asp:ListItem Text="Cricket" Value="1"></asp:ListItem>
                        <asp:ListItem Text="Hockey" Value="2"></asp:ListItem>
                        <asp:ListItem Text="Chess" Value="3"></asp:ListItem>
                    </asp:CheckBoxList>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Country
                </td>
                <td>
                    <asp:DropDownList ID="ddlEducation" runat="server">
                        <asp:ListItem Text="--Select Education--" Value="0" />
                        <asp:ListItem Text="B.Tech" Value="B.Tech" />
                        <asp:ListItem Text="MCA" Value="MCA" />
                        <asp:ListItem Text="MBA" Value="MBA" />
                        <asp:ListItem Text="AGBSC" Value="AGBSC" />
                        <asp:ListItem Text="MBBS" Value="MBBS" />
                    </asp:DropDownList>
                </td>
            </tr>
            <td class="style3">
                &nbsp;
            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return validation();" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
Share:

How to create dynamic textboxes and stored textboxes values save in SQL database in C#

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
        <asp:Table id="Table1" runat="server" BorderColor="Black" BorderStyle="Solid" BorderWidth="3px" Font-Bold="True" >
   
        </asp:Table>
<asp:PlaceHolder id="PlaceHolder1" runat="server">
</asp:PlaceHolder><BR><BR>
        <br />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    <asp:Button ID="btn" runat="server" Text="Button" onclick="btn_Click1" />
    </form>
    </body></html>
...................................................................................................................................
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 Default2 : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection(@"Data Source=COMTECH-PC\SQLEXPRESS;database=kabir;integrated security=true;");

     protected void Page_Load(object sender, EventArgs e)
    {
     
        if (ViewState["Count"] != null)
        {
         
          
            //AddTextBoxs();
            //AddButton();
            AddTextBoxs_Session();
         
        }
    }
     private void AddTextBoxs()
     {
         clear();
         int cnt = Convert.ToInt32(TextBox1.Text);
         TableHeaderRow htr = new TableHeaderRow();
         TableHeaderCell htc1 = new TableHeaderCell();
         htc1.Width = 100;
         htc1.Text = "Name";
         htr.Cells.Add(htc1);
         Table1.Rows.Add(htr);
         for (int i = 0; i < cnt; i++)
         {
             TableRow tr = new TableRow();
             TableCell tc1 = new TableCell();
             tc1.Width = 100;
             TextBox t = new TextBox();
             t.Width = 100;
             t.ID = "CN" + Table1.Rows.Count;
             tc1.Controls.Add(t);
             tr.Cells.Add(tc1);
             Table1.Rows.Add(tr);
           

         }


     }

     private void AddTextBoxs_Session()
     {
         clear();
         int cnt = Convert.ToInt32(TextBox1.Text);
         TableHeaderRow htr = new TableHeaderRow();
         TableHeaderCell htc1 = new TableHeaderCell();
         htc1.Width = 100;
         htc1.Text = "Name";
         htr.Cells.Add(htc1);
         Table1.Rows.Add(htr);
         for (int i = 0; i < cnt; i++)
         {
             TableRow tr = new TableRow();
             TableCell tc1 = new TableCell();
             tc1.Width = 100;
             TextBox t = new TextBox();
             t.Width = 100;
             t.ID = "CN" + Table1.Rows.Count;
             tc1.Controls.Add(t);
             tr.Cells.Add(tc1);
             Table1.Rows.Add(tr);
             cn.Open();
             SqlCommand cmd = new SqlCommand("alter table pratima add " + (t.ID).ToString() + " varchar(50)", cn);
             cmd.ExecuteNonQuery();
             cn.Close();

         }

     }

    //private void AddButton()
    //{
    //    Button b = new Button();
    //    b.ID = "btn";
    //    b.Text = "Button";
    //    b.Click += new System.EventHandler(btn_Click);
    //    PlaceHolder1.Controls.Add(b);
    //}
    protected void Button1_Click(object sender, EventArgs e)
    {
        AddTextBoxs();
       // if (ViewState["Count"] == null) AddButton();
        ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;

    }
  
    protected void Button2_Click(object sender, EventArgs e)
    {
      
       // AddButton();

        clear();
        AddTextBoxs();
        //if (ViewState["Count"] == null) AddButton();
        ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;
    }
  
    public void bindgrid()
    {
        //SqlConnection cn = new SqlConnection("Data Source=SQLDB;User ID=Demoh;Password=Demo1@");
        //SqlCommand cmd = new SqlCommand("select * from poll", cn);
        //DataTable dt = new DataTable();
        //SqlDataAdapter sa = new SqlDataAdapter();
        //cn.Open();
        //sa.SelectCommand = cmd;
        //cmd.ExecuteNonQuery();
        //sa.Fill(dt);
        //GridView1.DataSource = dt;
        //GridView1.DataBind();
    }
    public void clear()
    {
        Table1.Rows.Clear();
        for (int i = 0; i < Table1.Rows.Count; i++)
            Table1.Rows.RemoveAt(i);
    }

    protected void btn_Click1(object sender, EventArgs e)
    {
        //AddTextBoxs_Session();
        
        if (cn.State == ConnectionState.Closed)
            cn.Open();
        try
        {
            for (int i = 1; i < Table1.Rows.Count; i++)
            {
                //string dp = ((TextBox)Table1.Rows[i+1].FindControl("txtnm" + i+1)).Text;
                TextBox tnm = (TextBox)Table1.Rows[i].FindControl("CN" + i);

                //TextBox tsal = (TextBox)Table1.Rows[i].FindControl("txtsal" + i);
                //DropDownList tyear = (DropDownList)Table1.Rows[i].FindControl("dpl" + i);
                string colname = "CN" + i;
                string str="select * from pratima";
                SqlDataAdapter da=new SqlDataAdapter(str,cn);
                DataSet ds=new DataSet();
                da.Fill(ds);
                int k=Convert.ToInt32(ds.Tables[0].Rows.Count);
                if(k<=0)
                {
                SqlCommand cmd1 = new SqlCommand("insert into  pratima (" + colname + ") values('" + tnm.Text + "')",cn);
                cmd1.ExecuteNonQuery();
                }
                else
                {

                    SqlCommand cmd1 = new SqlCommand("update  pratima set " + colname + "='" + tnm.Text + "' where id="+k+"", cn);
                    cmd1.ExecuteNonQuery();
                }
                

                // bindgrid();
            }
        }
            catch(Exception ex)
            {
               
            }
        finally
            {
            cn.Close();
             clear();
            }

        }

        
    
}


Share:

Bind database table in html format at asp.net page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 id="Head1" runat="server">
    <title>Display Data in Dynamically Created Table</title>
</head>
<body>
    <form id="form1" runat="server">
        <table style="width: 50%; text-align: center; background-color: skyblue;">
            <tr>
                <td align="center">
                    <asp:PlaceHolder ID="DBDataPlaceHolder" runat="server"></asp:PlaceHolder>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
..............................................................
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.Text;  
  

public partial class Default2 : System.Web.UI.Page
{
 
        SqlDataAdapter da;  
        DataSet ds = new DataSet();  
        StringBuilder htmlTable = new StringBuilder();  
  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!Page.IsPostBack)  
                BindData();  
        }  
  
        private void BindData()  
        {  
            SqlConnection con = new SqlConnection();
            con.ConnectionString = @"Data Source=COMTECH-PC\SQLEXPRESS;Integrated Security=true;Initial Catalog=kabir";  
            SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);  
            da = new SqlDataAdapter(cmd);  
            da.Fill(ds);  
            con.Open();  
            cmd.ExecuteNonQuery();  
            con.Close();  
  
            htmlTable.Append("<table border='1'>");  
            htmlTable.Append("<tr style='background-color:green; color: White;'><th>ID.</th><th>Name</th><th>Salary</th></tr>");  
  
            if (!object.Equals(ds.Tables[0], null))  
            {  
                if (ds.Tables[0].Rows.Count > 0)  
                {  
  
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
                    {  
                        htmlTable.Append("<tr style='color: White;'>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["ID"] + "</td>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Name"] + "</td>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Salary"] + "</td>");  
                        htmlTable.Append("</tr>");  
                    }  
                    htmlTable.Append("</table>");  
                    DBDataPlaceHolder.Controls.Add(new Literal { Text = htmlTable.ToString() });  
                }  
                else  
                {  
                    htmlTable.Append("<tr>");  
                    htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");  
                    htmlTable.Append("</tr>");  
                }  
            }  
        }  
    }  
 

Share:

What is N-Tier Logic (Presentation,Business & Data Access Layer) in C#

.................................................................DAL........................................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
public DAL()
{
//
// TODO: Add constructor logic here
//
}

 
    public int recordInsert(string name,string pwd,int age,decimal salary,int mobile, string email,string image)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("sp_recordinsert",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name",name);
            cmd.Parameters.AddWithValue("@pwz",pwd);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@mobile", mobile);
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@image",image);
            con.Open();
            return cmd.ExecuteNonQuery();
         

        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
         con.Close();
        }

    }

    public int recordUpdate(int id, string name, string pwd, int age, decimal salary, int mobile, string email,string image)
    {
        try
        {
            SqlCommand cmd=new SqlCommand("sp_recordupdate",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name",name);
            cmd.Parameters.AddWithValue("@pwz", pwd);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@mobile", mobile);
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@id", id);
            cmd.Parameters.AddWithValue("@image",image);
            con.Open();
            return cmd.ExecuteNonQuery();
         
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

    public DataSet recordSelect()
    {
        try
        {
            SqlDataAdapter da=new SqlDataAdapter("sp_recordselect",con);
            DataSet ds=new DataSet();
            da.Fill(ds);
            return ds;
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }

    public int recordDelete(int id)
    {
     
      try
        {
            SqlCommand cmd = new SqlCommand("sp_recordDetete",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id",id);
            con.Open();
            return cmd.ExecuteNonQuery();
       

        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

    public DataSet getImage(int id)
    {
        try
        {
         
            SqlDataAdapter da = new SqlDataAdapter("select*from userRecord where id='"+id+"'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
             
       
        }
     
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
         
        }
    }
}
...................................................................BAL................................................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
public BAL()
{
//
// TODO: Add constructor logic here
//
}
    public DataSet retriveRecord()
    {
        DAL ob = new DAL();
        try
        {
         
            return ob.recordSelect();
        }

        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            ob = null;
        }
    }
    public int insertRecord_BAL(string name, string pwd, int age, decimal salary, int mobile, string email ,string image)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordInsert(name,  pwd,  age,  salary,  mobile,  email ,image);
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }
    public int deleteRecord(int id)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordDelete(id);
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {

        }
    }

    public int updateRecord( int id,string name,string pwd,int  age, decimal salary,int mobile, string email,string image)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordUpdate(id,name,pwd,age,salary,mobile,email,image);
        }
        catch(Exception ex)

        {
            throw;
        }
        finally
        {
        }
    }

    public DataSet find_image(int id)
    {
        DAL ob = new DAL();
        try
        {
            return ob.getImage(id);
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }
}
......................................................................UI...................................................................................
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 Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            showRecord();
        }
    }


    protected void showRecord()
    {
        BAL ob=new BAL();
        try
        {
            GridView1.DataSource = ob.retriveRecord();
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            throw;
        }
            finally
        {

        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        BAL ob=new BAL();
        try
        {
            int result = 0;
            int index=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            result = ob.deleteRecord(index);
            if(result>0)
            {
                Response.Write("<script>alert('Successfully deleted')</script>");
                showRecord(); ;
            }
            else
            {
                Response.Write("<script>alert('Not deleted')</script>");
            }
        }
        catch(Exception ex)
        {
            throw;

        }
        finally
        {

        }

       
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        BAL ob = new BAL();
        try
        {
            int result = 0;

            string name = TextBox1.Text;
            string pwd = TextBox2.Text;
            int age = Convert.ToInt32(TextBox4.Text);
            decimal salary = Convert.ToDecimal(TextBox5.Text);
            Int32 mobile = Convert.ToInt32(TextBox6.Text);
            string email = TextBox7.Text;
            string imagename = FileUpload1.FileName;
            string path = Server.MapPath(" ");
            string str = path + "/" + "image" + "/" + imagename;
            FileUpload1.PostedFile.SaveAs(str);
            string s = "image"+ "/" + imagename;
            result = ob.insertRecord_BAL(name, pwd, age, salary, mobile, email,s);
            if (result > 0)
            {
                Response.Write("<script>alert('Successfully saved')</script>");
                TextBox1.Text = "";
                TextBox2.Text = "";
                TextBox3.Text = "";
                TextBox4.Text = "";
                TextBox5.Text = "";
                TextBox6.Text = "";
                TextBox7.Text = "";
                showRecord();

            }
            else
            {
                Response.Write("<script>alert('Not saved')</script>");
            }

        }
        catch (Exception ex)
        {
        }
        finally
        {
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

        GridView1.EditIndex = -1;
        showRecord();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //BAL ob = new BAL();
        //ImageButton lb = (ImageButton)GridView1.FindControl("ImageButton1") as ImageButton;
        //ViewState["imageName"] = lb.ImageUrl;
        GridView1.EditIndex = e.NewEditIndex;
        showRecord();
     
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.EditIndex = -1;
        showRecord();

    }
    //public void DeletePysicalFiles(int id, string fileName)
    //{


    //    System.IO.File.Delete(Request.PhysicalApplicationPath + "Upload/" + fileName);

    //}
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        BAL ob=new BAL();
        try
        {
            int result = 0;
            int index = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox8") as TextBox;
            TextBox pwd = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox9") as TextBox;
            TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox10") as TextBox;
            TextBox salary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox11") as TextBox;
            TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox12") as TextBox;
            TextBox email = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox13") as TextBox;
            FileUpload fl = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload2") as FileUpload;
            ImageButton img=(ImageButton)GridView1.Rows[e.RowIndex].FindControl("ImageButton1") as   ImageButton;
         
            DataSet ds = new DataSet();
            ds = ob.find_image(index);
            string st=ds.Tables[0].Rows[0]["image"].ToString();

            System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("image\\") + st);
            if (fi.Exists)
            {
                fi.Delete();
            }
            string imagename = fl.FileName;
            string path = Server.MapPath(" ");
            string str = path + "/" + "image" + "/" + imagename;
            fl.PostedFile.SaveAs(str);
            result = ob.updateRecord(index, name.Text, pwd.Text, Convert.ToInt32(age.Text), Convert.ToDecimal(salary.Text), Convert.ToInt32(mobile.Text), email.Text,fl.FileName);
            showRecord();
            if (result > 0)
            {
                Response.Redirect("Default4.aspx?id="+index);
                //Response.Write("<script>alert('Sucessfully updated')</script>");

             
            }
            else
            {
                Response.Write("<script>alert('Not updated')</script>");
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
         
        }
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView1.PageIndex = -1;
        showRecord();
    }
}
...................................................................................................................................................................
Share:

Thursday, 31 December 2015

How to use if else inside the Repeater control using C#?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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">
    <div>
   
        <asp:DataList ID="DataList1" runat="server">
        </asp:DataList>
   
    </div>
    <asp:Repeater ID="Repeater1" runat="server"
        onitemcommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" CommandName="cmd" runat="server" Text='<%#Eval("name") %>'>LinkButton</asp:LinkButton>
    </ItemTemplate>
    </asp:Repeater>
    </form>
</body>
</html>
..............................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"server=COMTECH-PC\SQLEXPRESS;database=ShriGaneshayNamah;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = "select * from employee";
        SqlDataAdapter da = new SqlDataAdapter(str,con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if(e.CommandName=="cmd")
        {
            LinkButton lnk = (LinkButton)e.Item.FindControl("LinkButton1");
            string name = lnk.Text;
            if(name=="kul")
            {
                Response.Redirect("https://www.google.co.in/?gfe_rd=cr&ei=vlqFVr78G6fR8AfnlJ_wAQ&gws_rd=ssl");
            }
            else if(name=="raj")
            {
                Response.Redirect("https://www.facebook.com/");
            }
        }
    }
}

How to create Repeater paging in Asp.net using 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.Text;
using System.Data.SqlClient;
using System.Globalization;

public partial class ifrmenquire_kappl_awards : System.Web.UI.Page
{
    int totalCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
         
        }

        try
        {
            DataSet ds = new DataSet();
            String sql = "sp_get_award";

            SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
            adapter.Fill(ds);
            totalCount = ds.Tables[0].Rows.Count;
            bindData();
       
        }
        catch(Exception ex)
        {
        }
     
    }
    public void bindData()
    {
        try
        {
            DataSet ds = new DataSet();
            String sql = "sp_get_award";
            int val = Convert.ToInt16(txtHidden.Value);
            if (val <= 0)
                val = 0;

            SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
            adapter.Fill(ds, val, 9, "blogs_Posts");
            rptritems.DataSource = ds;
            rptritems.DataBind();

            if (val <= 0)
            {
                lnkBtnPrev.Visible = false;
                lnkBtnNext.Visible = true;
            }

            if (val >= 3)
            {
                lnkBtnPrev.Visible = true;
                lnkBtnNext.Visible = true;
            }

            if ((val + 3) >= totalCount)
            {
                lnkBtnNext.Visible = false;
            }
        }
        catch(Exception ex)
        {
        }
    }
    protected void lnkBtnPrev_Click(object sender, EventArgs e)
    {
        try
        {
            txtHidden.Value = Convert.ToString(Convert.ToInt16(txtHidden.Value) - 6);
            bindData();
        }
        catch (Exception ex)
        {
        }
    }
    protected void lnkBtnNext_Click(object sender, EventArgs e)
    {
        try
        {
            txtHidden.Value = Convert.ToString(Convert.ToInt16(txtHidden.Value) + 6);
            bindData();
        }
        catch(Exception ex)
        {
        }
     
    }
    private void LoadDataForAwards()
    {
        try
        {
            BlogsDAL dal = new BlogsDAL();
            DataTable dt = dal.LoadDataForAwardsPost(Util.GetSourceWebsite());
            rptritems.DataSource = dt;
            rptritems.DataBind();
        }
        catch(Exception ex)
        {
            throw;
        }
       
    }


    protected void rptritems_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try{
            if (e.CommandName == "cmd")
            {
                string str = "sp_get_award";
                SqlDataAdapter da = new SqlDataAdapter(str, Util.GetSourceWebsite());
                DataSet ds = new DataSet();
                da.Fill(ds);
                string name = ds.Tables[0].Rows[0]["Author"].ToString();
                if (name == "Abhilash")
                {
               
                    Response.Redirect("http://www.whyayurveda.org/author/abhilash-k.r.aspx");
                }
                else if (name == "Gita")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/gita-ramesh.aspx");
                }
                else if (name == "Abishek")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/abishek-k.r.aspx");
                }
                else if (name == "reeta-bhattacharjee")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/reeta-bhattacharjee.aspx");
                }
                else if (name == "ramesh")
                {
                    Response.Redirect("http://www.whyayurveda.org/author/ramesh-k.v.aspx");
                }
            }
        }
        catch(Exception ex)
        {
        }
    }
    protected void rptritems_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataSet ds = new DataSet();
                String sql = "sp_get_award";
                DateTime date;
                SqlDataAdapter adapter = new SqlDataAdapter(sql, Util.GetSourceWebsite());
                adapter.Fill(ds);
                string getdate = ds.Tables[0].Rows[0]["post_AddedDate"].ToString();
               
                date = Convert.ToDateTime(getdate);

                Label lblAnswer = e.Item.FindControl("Label1") as Label;
                lblAnswer.Text = date.ToString("ddd d MMM yyyy", CultureInfo.CreateSpecificCulture("en-US"));

               
            }
        }
        catch(Exception ex)
        {
        }
    }
}
................................................
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ifrmenquire_kappl_awards.aspx.cs" Inherits="ifrmenquire_kappl_awards" %>

<!DOCTYPE html>
<html lang="en-US">
<head runat="server">
    <title></title>
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="css/kappl-awards.css" />

    <script src="css/jQuery1.9.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server" class="pad10awd">
    <div id="divTop5" runat="server">
                </div>
    <div class="blogwhy">
        <ul class="whyayurveda">
            <asp:Repeater ID="rptritems" runat="server" 
                onitemcommand="rptritems_ItemCommand" onitemdatabound="rptritems_ItemDataBound" 
                >
                <ItemTemplate>
                    <li class="blog<%# DataBinder.Eval(Container.DataItem, "post_kid")%>">
                        <div class="whytitle">
                            <a onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);" class="posttitle">
                                <%# DataBinder.Eval(Container.DataItem, "post_title")%></a>
                        </div>
                        <div class="whydescription">
                            <div class="postsummary">
                                <%# DataBinder.Eval(Container.DataItem, "post_summary")%>
                            </div>
                            <div class="hidden postcontent">
                                <%# DataBinder.Eval(Container.DataItem, "post_title")%>
                            </div>
                            <div class="hidden mainurulwhy">
                                <%# DataBinder.Eval(Container.DataItem, "post_mainimagename")%>
                            </div>
                        </div>
                        <div class="whypic">
                            <a><span>
                                <img class="img1" src=" <%# DataBinder.Eval(Container.DataItem, "post_MainImageName")%>" />
                                <span class="viewdtl" onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);">
                                </span></a>
                        </div>
                        <div class="whyposted">
                            <p>
                                Posted By 
                                <a target="_blank" href="<%# DataBinder.Eval(Container.DataItem, "author")%>">
                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="cmd" Text='<%# DataBinder.Eval(Container.DataItem, "author")%>'>LinkButton</asp:LinkButton>
                                    
                                    
                        <%-- <%# DataBinder.Eval(Container.DataItem, "author")%>--%>

                                  </a>
                                  posted on  
                                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                                  
<%--                                 <%#Eval("post_AddedDate", "{0:D}")%>
--%>                                at
                                <br />
                                <%#Eval("post_AddedDate", "{0:t}")%>
                            </p>
                        </div>
                        <div class="learnmore">
                            <a onclick="blogshow( <%# DataBinder.Eval(Container.DataItem, "post_kid")%>);">Learn
                                More</a>
                        </div>
                    </li>
                </ItemTemplate>
            </asp:Repeater>
        </ul>
        <div class="paging">
            <input id="txtHidden" style="width: 28px" type="hidden" value="0" runat="server" /><hr>
            <asp:LinkButton ID="lnkBtnPrev" runat="server" Font-Underline="False" OnClick="lnkBtnPrev_Click"
                Font-Bold="True"><span class="prevpanel">← Prev</span></asp:LinkButton>
            &nbsp;&nbsp;
            <asp:LinkButton ID="lnkBtnNext" runat="server" Font-Underline="False" OnClick="lnkBtnNext_Click"
                Font-Bold="True"><span class="nextpanel">Next →</asp:LinkButton>
        </div>
    </div>
    <div class="blogwhyfull hideme">
        <div class="basecent">
            <div class="close-dtl">
                <a onclick="$('.blogwhyfull').hide();">x</a>
            </div>
            <ul class="whyayurvedapop">
                <li>
                    <div class="whytitle1 cnt">
                    </div>
                    <div class="whyposted1 cnt">
                    </div>
                    <div class="whydescription1 cnt sammary">
                    </div>
                    <div class="whypic1">
                        <img class="img2" alt="blog" />
                    </div>
                    <div class="whydescription1 cnt maindesc">
                    </div>
                    <p>
                        <strong>Courtesy:</strong> <a href="http://www.whyayurveda.org/products/2014/09/22/ayurveda-for-hair-diseases.aspx">Whyayurveda</a>
                    </p>
                    <div class="arrows-nex-prev pop">
                  


                    <a  href="http://www.kairaliproducts.in/enqurie-now"><span class="prevpanel">Enquire Now</span>
                    </a>
                    <a  href="http://www.kairaliproducts.in/online-consultation"><span class="nextpanel">
                            Free Online Consultation</span> </a>
                    </div>
                </li>
            </ul>
        </div>
    </div>
    </form>

    <script language="javascript">
        function blogshow(id) {
            var options = {};
            $(".cnt").empty();
            $(".whytitle1").html($(".blog" + id).find('.posttitle').html());
            $(".sammary").html($(".blog" + id).find('.postsummary').html());
            $(".maindesc").html($(".blog" + id).find('.postcontent').html());
            $(".whyposted1").html($(".blog" + id).find('.whyposted').html());
            $(".img2").attr('src', $(".blog" + id).find('.img1').attr('src'));
            $("#alinkaway").attr('href', $(".blog" + id).find('.mainurulwhy').html());
            $(".blogwhyfull").show();
        }
        $(document).ready(function() {
            if (getParameterByName('id') > 0) {
                blogshow(getParameterByName('id'));
            }
        });
        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    </script>

</body>
</html>

Monday, 31 August 2015

Multi-Threading Program

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

namespace MultiTheadingAbort  
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread th = new Thread(writey);
            if (th.IsAlive)
            {
                th.Start();
                th.Abort();
            }
            for (int i = 0; i <= 10;i++ )
            {
                Console.WriteLine("hello");
            }
            Console.Read();
        }

        private static void writey()
        {
            for (int i = 0; i <= 9;i++ )
            {
                Console.WriteLine("kul");
            }
        }

    }
}

Threading Program

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

namespace mThreading
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread th = new Thread(writey);
            th.Start();
            for (int i = 0; i <= 10;i++ )
            {
                Console.WriteLine("hello");
            }
            Console.Read();
        }
        private static void writey()
        {
            for (int i = 0; i <= 9;i++ )
            {
                Console.WriteLine("world");
            }
        }
    }
}

What is Copy Constructor in C#? Example.

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

namespace CopyConstructor
{
    class Program
    {
        static void Main(string[] args)
        {
            Test T = new Test(10,20);
            T.Print();
            Console.Read();
        }
    }
    class Test

    {
        int A, B;
        public Test(int X,int Y)
        {
            A = X;
            B = Y;
        }
        public Test(Test T)
        {
           A = T.A;
           B = T.B;
        }
        public void Print()
        {
            Console.Write("A={0} and B={1}",A,B);
        }
 
    }
}

Parameterized Constructor

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

namespace ParameterizedConstructorExamples
{
    class Program
    {
        static void Main(string[] args)
        {
            Test T = new Test(10,20);
            T.Print();
            Console.Read();
        }
    }
    class Test
    {
        int A, B;
        public Test(int X, int Y)
        {
            A = X;
            B = Y;
        }
        public void Print()
        {
            Console.Write("A ={0} and B={1}",A,B);
        }
    }
}

How to find distinct element from multiple time's coming elements in the Array in C#

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

namespace FromMultipleElementsFindDistinctEach
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] ar = new int [] {1,1,1,2,2,2,2,2,3,4,4};
            var distinct = new HashSet<int>(ar);
            foreach (int i in distinct)
            {
                Console.Write(i+",");
            }
            Console.Read();
        }
    }
}

User valid or none valid procedure in SQL Server

create database zz
-create table
create table users (id int identity(1,1),username varchar(50),password
varchar(50))
--insert values in table
insert into users values('kul',123)
--create procedure
create proc getoutput
(
@UserName varchar(50),
@password varchar(50),
@UName varchar(50) OUTPUT,
@Pword varchar(50) OUTPUT
)
as
Begin
IF EXISTS(Select * FROM users WHERE UserName = @UserName AND Password = @password)
Begin
set @UName=@UserName
set @Pword=@password
end
else
begin
print 'You are not a valid user.'
end
End
--call procedure
declare @UsName varchar(50);
declare @pass varchar(50);
exec getoutput 'kul','1223' ,@UName=@UsName output,@Pword=@pass output
print @UsName
print @pass

        

Tuesday, 28 July 2015

How to get Textbox value in XML format and pass as a parameter using Asp.Net C#

       XmlDocument xmldoc=new XmlDocument();
        XmlElement emp_name = xmldoc.CreateElement(TextBox1.Text);
        string name= emp_name.Name;
        XmlElement emp_salary = xmldoc.CreateElement(TextBox2.Text);
        decimal salary = Convert.ToDecimal(emp_salary.Name);
        string str = "insert into emp values('"+name+"',"+salary+")";
        SqlCommand cmd = new SqlCommand(str,con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        BindGrid();
        Response.Write("<script>alert('Successfully saved !')</script>");
        TextBox1.Text = string.Empty;
        TextBox2.Text = string.Empty;

Friday, 17 July 2015

How to create stored procedure for Country, State, City for saving in SQL database?

Create database USERS
USE USERS

Create table TblCountry(CId int identity(1,1) primary key,Country varchar(50))
Create table TblState(SId int identity(1,1) primary key,FK_CountryId int references TblCountry(CId),State varchar(50))
Create table TblCity(CityId int identity(1,1) primary key,FK_StateId int references TblState(SId),FK_CountryId int,City varchar(50))

create proc abc
(
@country varchar(100),
@state varchar(100),
@city varchar(200)
)
as
begin
if not exists(select * from TblCountry where country=@country)
begin
insert into TblCountry(country) values(@country)
end
declare @countryid int;
select @countryid=CId from TblCountry where country=@country
if not exists(select * from TblState where State=@state)
begin
insert into TblState(FK_CountryId,state) values(@countryid,@state)
end

declare @stateid int;
select @stateid=SId from TblState where state=@state
if not exists(select * from TblCity where city=@city)
begin
insert into TblCity(FK_StateId,FK_CountryId,city)
values(@stateid,@countryid,@city)
end

end


select * from TblCountry
select * from TblState
select * from TblCity

execute dbo.abc 'America','LansAngile','Gaziabad'

Tuesday, 23 June 2015

Javascript Validation Form

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <%--this code for disable cut copy paste but enter number by key--%>
    <script language="javascript">
        function whichButton(event) {
            if (event.button == 2)//RIGHT CLICK
            {
                alert("Not Allow Right Click!");
            }

        }
        function noCTRL(e) {
            var code = (document.all) ? event.keyCode : e.which;

            var msg = "Sorry, this functionality is disabled.";
            if (parseInt(code) == 17) //CTRL
            {
                alert(msg);
                window.event.returnValue = false;
            }
        }
    </script>
    <%--this code for only numeric and strengh completed check--%>
    <script type="text/javascript">
        function ValidNumeric() {
            var p = document.getElementById('<%=txtpin.ClientID %>').value;
            var charCode = (event.which) ? event.which : event.keyCode;
            if (charCode >= 48 && charCode <= 57) {
                return true;
            }
            else if (p < 5) {
                alert('Only numeric number allow !');
                return false;
            }
            else {
                alert('Pin strengh has completed !');
                return false;
            }
        }
    </script>
    <script language="javascript" type="text/javascript">
        function validation() {
            var mobile = document.getElementById('<%=txtmbl.ClientID %>').value;
            var Email = document.getElementById('<%=txtmail.ClientID %>').value;
            var WebUrl = document.getElementById('<%=txturl.ClientID %>').value;
            var p = document.getElementById('<%=txtpin.ClientID %>').value;


            if (p == "") {
                alert("Enter Your Pin");
                document.getElementById("<%=txtpin.ClientID%>").focus();
                return false;
            }


            //            var digits = "0123456789";
            //            var temp;
            //            for (var i = 0; i < document.getElementById("<%=txtpin.ClientID %>").value.length; i++) {
            //                temp = document.getElementById("<%=txtpin.ClientID%>").value.substring(i, i + 1);
            //                if (digits.indexOf(temp) == -1) {
            //                    alert("Please enter correct pin code");
            //                    document.getElementById("<%=txtpin.ClientID%>").focus();
            //                    return false;
            //                }
            //            }

            if (WebUrl == "") {
                alert("Enter Your URL");
                document.getElementById("<%=txturl.ClientID %>").focus();
                return false;
            }
            var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
            var matchURL = WebUrl.match(Url);
            if (matchURL == null) {
                alert("Web URL does not look valid");
                document.getElementById("<%=txturl.ClientID %>").focus();
                return false;
            }

            if (Email == "") {
                alert("Enter Your Email");
                document.getElementById("<%=txtmail.ClientID%>").focus();
                return false;
            }
            var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
            var EmailmatchArray = Email.match(emailPat);
            if (EmailmatchArray == null) {
                alert("Your email must be this format eg. k@gmail.com !");
                document.getElementById("<%=txtmail.ClientID%>").focus();
                return false;
            }
            if (mobile == "") {
                alert("Enter Your Mobile Number !");
                document.getElementById("<%=txtmbl.ClientID%>").focus();
                return false;
            }
            var phoneno = /^\d{10}$/
            var EmailmatchArray = mobile.match(phoneno);
            if (EmailmatchArray == null) {
                alert("Number must be 10 digit !");
                document.getElementById("<%=txtmbl.ClientID%>").focus();
                return false;
            }

            if (document.getElementById('<%=txtname.ClientID%>').value == "") {
                alert('First Name must be required !');
                document.getElementById('<%=txtname.ClientID%>').focus();
                return false;
            }
            if (document.getElementById("<%=txtlname.ClientID%>").value == "") {
                alert('Last Name must be required !');
                document.getElementById("<%=txtlname.ClientID%>").focus();
                return false;
            }
            if (!document.getElementById('<%=rdomale.ClientID%>').checked && !document.getElementById('<%=rdofemale.ClientID%>').checked) {
                alert("Gender must be required !");
                document.getElementById('<%=rdomale.ClientID%>').focus();
                return false;
            }
            var atLeast = 1
            var CHK = document.getElementById('<%=CheckBoxList1.ClientID%>');
            var checkbox = CHK.getElementsByTagName("input");
            var counter = 0;
            for (var i = 0; i < checkbox.length; i++) {
                if (checkbox[i].checked) {
                    counter++;
                }
            }
            if (atLeast > counter) {
                alert('Please select one hobbies !');

                document.getElementById('<%=CheckBoxList1.ClientID%>').focus();
                return false;

            }

            var result = document.getElementById('<%=ddlEducation.ClientID%>').value.toString();
            if (result == "0") {
                alert('Please select a streem !');
                document.getElementById('<%=ddlEducation.ClientID%>').focus();
                return false;

            }
        }

    </script>
    <%--var ddltrader = document.getElementById('<%=ddltradername.ClientID%>');
            var ddlproductype1 = ddltrader.options[ddltrader.selectedIndex].value;--%>
    <style type="text/css">
        .style1
        {
            width: 50%;
            background-color: #FFCC99;
        }
        .style3
        {
            width: 68px;
        }
    </style>
</head>
<body>
    <form runat="server" id="form1">
    <table align="center" class="style1">
        <tr>
            <td class="style3">
                Pin
            </td>
            <td>
                <asp:TextBox ID="txtpin" runat="server" MaxLength="5" onMouseDown="whichButton(event)"
                    onKeyDown="return noCTRL(event)" onkeypress="return ValidNumeric()"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Url
            </td>
            <td>
                <asp:TextBox ID="txturl" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Email
            </td>
            <td>
                <asp:TextBox ID="txtmail" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td class="style3">
                Mobile
            </td>
            <td>
                <asp:TextBox ID="txtmbl" MaxLength="10" onkeypress="return ValidNumeric()" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <tr>
                <td class="style3">
                    First Name
                </td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Last Name
                </td>
                <td>
                    <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Gender
                </td>
                <td>
                    <asp:RadioButton ID="rdomale" runat="server" GroupName="k" name="gender" Text="Male" />
                    <asp:RadioButton ID="rdofemale" runat="server" GroupName="k" name="gender" Text="Female" />
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Hobbies
                </td>
                <td>
                    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
                        <asp:ListItem Text="Cricket" Value="1"></asp:ListItem>
                        <asp:ListItem Text="Hockey" Value="2"></asp:ListItem>
                        <asp:ListItem Text="Chess" Value="3"></asp:ListItem>
                    </asp:CheckBoxList>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Country
                </td>
                <td>
                    <asp:DropDownList ID="ddlEducation" runat="server">
                        <asp:ListItem Text="--Select Education--" Value="0" />
                        <asp:ListItem Text="B.Tech" Value="B.Tech" />
                        <asp:ListItem Text="MCA" Value="MCA" />
                        <asp:ListItem Text="MBA" Value="MBA" />
                        <asp:ListItem Text="AGBSC" Value="AGBSC" />
                        <asp:ListItem Text="MBBS" Value="MBBS" />
                    </asp:DropDownList>
                </td>
            </tr>
            <td class="style3">
                &nbsp;
            </td>
            <td>
                <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return validation();" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Monday, 1 June 2015

How to create dynamic textboxes and stored textboxes values save in SQL database in C#

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
        <asp:Table id="Table1" runat="server" BorderColor="Black" BorderStyle="Solid" BorderWidth="3px" Font-Bold="True" >
   
        </asp:Table>
<asp:PlaceHolder id="PlaceHolder1" runat="server">
</asp:PlaceHolder><BR><BR>
        <br />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    <asp:Button ID="btn" runat="server" Text="Button" onclick="btn_Click1" />
    </form>
    </body></html>
...................................................................................................................................
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 Default2 : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection(@"Data Source=COMTECH-PC\SQLEXPRESS;database=kabir;integrated security=true;");

     protected void Page_Load(object sender, EventArgs e)
    {
     
        if (ViewState["Count"] != null)
        {
         
          
            //AddTextBoxs();
            //AddButton();
            AddTextBoxs_Session();
         
        }
    }
     private void AddTextBoxs()
     {
         clear();
         int cnt = Convert.ToInt32(TextBox1.Text);
         TableHeaderRow htr = new TableHeaderRow();
         TableHeaderCell htc1 = new TableHeaderCell();
         htc1.Width = 100;
         htc1.Text = "Name";
         htr.Cells.Add(htc1);
         Table1.Rows.Add(htr);
         for (int i = 0; i < cnt; i++)
         {
             TableRow tr = new TableRow();
             TableCell tc1 = new TableCell();
             tc1.Width = 100;
             TextBox t = new TextBox();
             t.Width = 100;
             t.ID = "CN" + Table1.Rows.Count;
             tc1.Controls.Add(t);
             tr.Cells.Add(tc1);
             Table1.Rows.Add(tr);
           

         }


     }

     private void AddTextBoxs_Session()
     {
         clear();
         int cnt = Convert.ToInt32(TextBox1.Text);
         TableHeaderRow htr = new TableHeaderRow();
         TableHeaderCell htc1 = new TableHeaderCell();
         htc1.Width = 100;
         htc1.Text = "Name";
         htr.Cells.Add(htc1);
         Table1.Rows.Add(htr);
         for (int i = 0; i < cnt; i++)
         {
             TableRow tr = new TableRow();
             TableCell tc1 = new TableCell();
             tc1.Width = 100;
             TextBox t = new TextBox();
             t.Width = 100;
             t.ID = "CN" + Table1.Rows.Count;
             tc1.Controls.Add(t);
             tr.Cells.Add(tc1);
             Table1.Rows.Add(tr);
             cn.Open();
             SqlCommand cmd = new SqlCommand("alter table pratima add " + (t.ID).ToString() + " varchar(50)", cn);
             cmd.ExecuteNonQuery();
             cn.Close();

         }

     }

    //private void AddButton()
    //{
    //    Button b = new Button();
    //    b.ID = "btn";
    //    b.Text = "Button";
    //    b.Click += new System.EventHandler(btn_Click);
    //    PlaceHolder1.Controls.Add(b);
    //}
    protected void Button1_Click(object sender, EventArgs e)
    {
        AddTextBoxs();
       // if (ViewState["Count"] == null) AddButton();
        ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;

    }
  
    protected void Button2_Click(object sender, EventArgs e)
    {
      
       // AddButton();

        clear();
        AddTextBoxs();
        //if (ViewState["Count"] == null) AddButton();
        ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;
    }
  
    public void bindgrid()
    {
        //SqlConnection cn = new SqlConnection("Data Source=SQLDB;User ID=Demoh;Password=Demo1@");
        //SqlCommand cmd = new SqlCommand("select * from poll", cn);
        //DataTable dt = new DataTable();
        //SqlDataAdapter sa = new SqlDataAdapter();
        //cn.Open();
        //sa.SelectCommand = cmd;
        //cmd.ExecuteNonQuery();
        //sa.Fill(dt);
        //GridView1.DataSource = dt;
        //GridView1.DataBind();
    }
    public void clear()
    {
        Table1.Rows.Clear();
        for (int i = 0; i < Table1.Rows.Count; i++)
            Table1.Rows.RemoveAt(i);
    }

    protected void btn_Click1(object sender, EventArgs e)
    {
        //AddTextBoxs_Session();
        
        if (cn.State == ConnectionState.Closed)
            cn.Open();
        try
        {
            for (int i = 1; i < Table1.Rows.Count; i++)
            {
                //string dp = ((TextBox)Table1.Rows[i+1].FindControl("txtnm" + i+1)).Text;
                TextBox tnm = (TextBox)Table1.Rows[i].FindControl("CN" + i);

                //TextBox tsal = (TextBox)Table1.Rows[i].FindControl("txtsal" + i);
                //DropDownList tyear = (DropDownList)Table1.Rows[i].FindControl("dpl" + i);
                string colname = "CN" + i;
                string str="select * from pratima";
                SqlDataAdapter da=new SqlDataAdapter(str,cn);
                DataSet ds=new DataSet();
                da.Fill(ds);
                int k=Convert.ToInt32(ds.Tables[0].Rows.Count);
                if(k<=0)
                {
                SqlCommand cmd1 = new SqlCommand("insert into  pratima (" + colname + ") values('" + tnm.Text + "')",cn);
                cmd1.ExecuteNonQuery();
                }
                else
                {

                    SqlCommand cmd1 = new SqlCommand("update  pratima set " + colname + "='" + tnm.Text + "' where id="+k+"", cn);
                    cmd1.ExecuteNonQuery();
                }
                

                // bindgrid();
            }
        }
            catch(Exception ex)
            {
               
            }
        finally
            {
            cn.Close();
             clear();
            }

        }

        
    
}


Bind database table in html format at asp.net page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 id="Head1" runat="server">
    <title>Display Data in Dynamically Created Table</title>
</head>
<body>
    <form id="form1" runat="server">
        <table style="width: 50%; text-align: center; background-color: skyblue;">
            <tr>
                <td align="center">
                    <asp:PlaceHolder ID="DBDataPlaceHolder" runat="server"></asp:PlaceHolder>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
..............................................................
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.Text;  
  

public partial class Default2 : System.Web.UI.Page
{
 
        SqlDataAdapter da;  
        DataSet ds = new DataSet();  
        StringBuilder htmlTable = new StringBuilder();  
  
        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!Page.IsPostBack)  
                BindData();  
        }  
  
        private void BindData()  
        {  
            SqlConnection con = new SqlConnection();
            con.ConnectionString = @"Data Source=COMTECH-PC\SQLEXPRESS;Integrated Security=true;Initial Catalog=kabir";  
            SqlCommand cmd = new SqlCommand("SELECT * FROM employee", con);  
            da = new SqlDataAdapter(cmd);  
            da.Fill(ds);  
            con.Open();  
            cmd.ExecuteNonQuery();  
            con.Close();  
  
            htmlTable.Append("<table border='1'>");  
            htmlTable.Append("<tr style='background-color:green; color: White;'><th>ID.</th><th>Name</th><th>Salary</th></tr>");  
  
            if (!object.Equals(ds.Tables[0], null))  
            {  
                if (ds.Tables[0].Rows.Count > 0)  
                {  
  
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
                    {  
                        htmlTable.Append("<tr style='color: White;'>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["ID"] + "</td>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Name"] + "</td>");  
                        htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Salary"] + "</td>");  
                        htmlTable.Append("</tr>");  
                    }  
                    htmlTable.Append("</table>");  
                    DBDataPlaceHolder.Controls.Add(new Literal { Text = htmlTable.ToString() });  
                }  
                else  
                {  
                    htmlTable.Append("<tr>");  
                    htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");  
                    htmlTable.Append("</tr>");  
                }  
            }  
        }  
    }  
 

Saturday, 30 May 2015

What is N-Tier Logic (Presentation,Business & Data Access Layer) in C#

.................................................................DAL........................................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
public DAL()
{
//
// TODO: Add constructor logic here
//
}

 
    public int recordInsert(string name,string pwd,int age,decimal salary,int mobile, string email,string image)
    {
        try
        {
            SqlCommand cmd = new SqlCommand("sp_recordinsert",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name",name);
            cmd.Parameters.AddWithValue("@pwz",pwd);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@mobile", mobile);
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@image",image);
            con.Open();
            return cmd.ExecuteNonQuery();
         

        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
         con.Close();
        }

    }

    public int recordUpdate(int id, string name, string pwd, int age, decimal salary, int mobile, string email,string image)
    {
        try
        {
            SqlCommand cmd=new SqlCommand("sp_recordupdate",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@name",name);
            cmd.Parameters.AddWithValue("@pwz", pwd);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@salary", salary);
            cmd.Parameters.AddWithValue("@mobile", mobile);
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@id", id);
            cmd.Parameters.AddWithValue("@image",image);
            con.Open();
            return cmd.ExecuteNonQuery();
         
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

    public DataSet recordSelect()
    {
        try
        {
            SqlDataAdapter da=new SqlDataAdapter("sp_recordselect",con);
            DataSet ds=new DataSet();
            da.Fill(ds);
            return ds;
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }

    public int recordDelete(int id)
    {
     
      try
        {
            SqlCommand cmd = new SqlCommand("sp_recordDetete",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@id",id);
            con.Open();
            return cmd.ExecuteNonQuery();
       

        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            con.Close();
        }
    }

    public DataSet getImage(int id)
    {
        try
        {
         
            SqlDataAdapter da = new SqlDataAdapter("select*from userRecord where id='"+id+"'", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
             
       
        }
     
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
         
        }
    }
}
...................................................................BAL................................................................................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
public BAL()
{
//
// TODO: Add constructor logic here
//
}
    public DataSet retriveRecord()
    {
        DAL ob = new DAL();
        try
        {
         
            return ob.recordSelect();
        }

        catch(Exception ex)
        {
            throw;
        }
        finally
        {
            ob = null;
        }
    }
    public int insertRecord_BAL(string name, string pwd, int age, decimal salary, int mobile, string email ,string image)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordInsert(name,  pwd,  age,  salary,  mobile,  email ,image);
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }
    public int deleteRecord(int id)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordDelete(id);
        }
        catch(Exception ex)
        {
            throw;
        }
        finally
        {

        }
    }

    public int updateRecord( int id,string name,string pwd,int  age, decimal salary,int mobile, string email,string image)
    {
        DAL ob = new DAL();
        try
        {
            return ob.recordUpdate(id,name,pwd,age,salary,mobile,email,image);
        }
        catch(Exception ex)

        {
            throw;
        }
        finally
        {
        }
    }

    public DataSet find_image(int id)
    {
        DAL ob = new DAL();
        try
        {
            return ob.getImage(id);
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
        }
    }
}
......................................................................UI...................................................................................
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 Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            showRecord();
        }
    }


    protected void showRecord()
    {
        BAL ob=new BAL();
        try
        {
            GridView1.DataSource = ob.retriveRecord();
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            throw;
        }
            finally
        {

        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        BAL ob=new BAL();
        try
        {
            int result = 0;
            int index=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            result = ob.deleteRecord(index);
            if(result>0)
            {
                Response.Write("<script>alert('Successfully deleted')</script>");
                showRecord(); ;
            }
            else
            {
                Response.Write("<script>alert('Not deleted')</script>");
            }
        }
        catch(Exception ex)
        {
            throw;

        }
        finally
        {

        }

       
    }
    protected void Button1_Click1(object sender, EventArgs e)
    {
        BAL ob = new BAL();
        try
        {
            int result = 0;

            string name = TextBox1.Text;
            string pwd = TextBox2.Text;
            int age = Convert.ToInt32(TextBox4.Text);
            decimal salary = Convert.ToDecimal(TextBox5.Text);
            Int32 mobile = Convert.ToInt32(TextBox6.Text);
            string email = TextBox7.Text;
            string imagename = FileUpload1.FileName;
            string path = Server.MapPath(" ");
            string str = path + "/" + "image" + "/" + imagename;
            FileUpload1.PostedFile.SaveAs(str);
            string s = "image"+ "/" + imagename;
            result = ob.insertRecord_BAL(name, pwd, age, salary, mobile, email,s);
            if (result > 0)
            {
                Response.Write("<script>alert('Successfully saved')</script>");
                TextBox1.Text = "";
                TextBox2.Text = "";
                TextBox3.Text = "";
                TextBox4.Text = "";
                TextBox5.Text = "";
                TextBox6.Text = "";
                TextBox7.Text = "";
                showRecord();

            }
            else
            {
                Response.Write("<script>alert('Not saved')</script>");
            }

        }
        catch (Exception ex)
        {
        }
        finally
        {
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

        GridView1.EditIndex = -1;
        showRecord();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //BAL ob = new BAL();
        //ImageButton lb = (ImageButton)GridView1.FindControl("ImageButton1") as ImageButton;
        //ViewState["imageName"] = lb.ImageUrl;
        GridView1.EditIndex = e.NewEditIndex;
        showRecord();
     
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.EditIndex = -1;
        showRecord();

    }
    //public void DeletePysicalFiles(int id, string fileName)
    //{


    //    System.IO.File.Delete(Request.PhysicalApplicationPath + "Upload/" + fileName);

    //}
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        BAL ob=new BAL();
        try
        {
            int result = 0;
            int index = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
            TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox8") as TextBox;
            TextBox pwd = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox9") as TextBox;
            TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox10") as TextBox;
            TextBox salary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox11") as TextBox;
            TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox12") as TextBox;
            TextBox email = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox13") as TextBox;
            FileUpload fl = (FileUpload)GridView1.Rows[e.RowIndex].FindControl("FileUpload2") as FileUpload;
            ImageButton img=(ImageButton)GridView1.Rows[e.RowIndex].FindControl("ImageButton1") as   ImageButton;
         
            DataSet ds = new DataSet();
            ds = ob.find_image(index);
            string st=ds.Tables[0].Rows[0]["image"].ToString();

            System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("image\\") + st);
            if (fi.Exists)
            {
                fi.Delete();
            }
            string imagename = fl.FileName;
            string path = Server.MapPath(" ");
            string str = path + "/" + "image" + "/" + imagename;
            fl.PostedFile.SaveAs(str);
            result = ob.updateRecord(index, name.Text, pwd.Text, Convert.ToInt32(age.Text), Convert.ToDecimal(salary.Text), Convert.ToInt32(mobile.Text), email.Text,fl.FileName);
            showRecord();
            if (result > 0)
            {
                Response.Redirect("Default4.aspx?id="+index);
                //Response.Write("<script>alert('Sucessfully updated')</script>");

             
            }
            else
            {
                Response.Write("<script>alert('Not updated')</script>");
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
         
        }
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView1.PageIndex = -1;
        showRecord();
    }
}
...................................................................................................................................................................

Popular

Total Pageviews

Archive