Wednesday 30 October 2013

How to find largest number in c | largest number examples.

How to find largest number in c | largest number examples.
Find largest number in c language without using  any loop with examples.


int maxnumber(int num1, int num2, int num3)
{
    int largestnumber;
        largestnumber=int num1; /*  Assume number 1 is largest number*/
        if (num2 > largestumber)
        {
            largetnumber=num2;   /* number 2 is largest number*/

        }
if (num3 > largestnumber)
{
largestnumber=num3;

}

return largestnumber;
}


we can do this by using for loop but here i have shown how to find out largest number using

if statement.

Tuesday 29 October 2013

Difference between Delete |Truncate | Drop in Sql server

Difference between Delete |Truncate | Drop  in Sql server

in this article i am goig to show you what is difference between delete and truncate and
drop command.


1->Delete

Delete command mostly use for delete single row or multiple row or delete all the row in

table.

take an examples ..
delete stud .
Will delete all rows in stud table.
now ,
delete from stud where condition..
will delete single or multiple record.
it is faster slower than truncate.
we can rollback .



2->Truncate.
Will delete all the data from table .
we can not specify where condition.
Faster than delete .
we can't rollback until we use transaction.
truncate table tablename


3-> drop

to delete the table also with data.
drop table tablename.
rollback but in transaction.


remember one thing once we committed we wont undo record or table in delete or truncate or

drop command.


begin tran

delete  fee
rollback tran

begin tran
delete from stud where id=104

drop table stud

delete will keep your identity as well.
second time entry will tale last id number where as in truncate that will start from 1.

Wednesday 23 October 2013

How to upload multiple file in c# | asp.net | Created directory of file name

How to upload multiple file in c# | asp.net | Created directory of file name
How to upload multiple file in asp.net with directory creation.
In this article we are going to learn how to upload multiple files in asp.net with c# code.
We can also find out if file has already uploaded then there will be directory creation with existing file name.
Lets take a examples ..
If i want to upload my resume file and there is three resume so what i need to do is , first of all i will select my resume 1

then 2 and last 3..
while uploading 3 files the resume1.doc , resume2.doc , resume3.doc will be selected at same time same names directory will

be created ..
but if you have already added or uploaded any of resume out of this then it will inform you that file already exists.

import using System.IO; namespace.

.aspx page



  <tr><td><asp:FileUpload runat="server" ID="fp1" /></td></tr>
  <tr><td><asp:FileUpload runat="server" ID="fp2" /></td></tr>
  <tr><td><asp:FileUpload runat="server" ID="fp3" /></td></tr>



now code to .cs page.


  private void Fileupload()
        {
            if (fp1.HasFile)
                {
                   
                   
                    string filename = fp1.FileName;
                  string str=  FunchekFilealreadythere(filename);
                  String filePath = Server.MapPath(@"~/upload_resume/"+str+"/"+ fp1.FileName);
                 fp1.SaveAs(filePath);//will add file name in file name directory.
            }

                if (fp2.HasFile)
                {
                 string filename1 = fp2.FileName;
                 string str1 = FunchekFilealreadythere(filename1);
                 String filePath1 = Server.MapPath(@"~/upload_resume/" + str1 + "/" + fp2.FileName);
                 fp2.SaveAs(filePath1);

                }


                if (fp3.HasFile)
                {
                    string filename2 = fp3.FileName;
                    string str2 = FunchekFilealreadythere(filename2);
                    String filePath2 = Server.MapPath(@"~/upload_resume/" + str2 + "/" + fp3.FileName);
                    fp3.SaveAs(filePath2);

                }


           
            else
            {
                Response.Write("uploaded");
            }
        }

        public string    FunchekFilealreadythereg filename)
        {
            string nm=filename ;
            string[] fnm=new string [1];
            fnm=nm .Split ('.');//will just take file name not extension.


            if (!System.IO.Directory.Exists(Server.MapPath(@"~/upload_resume/" + fnm[0] + "")))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath(@"~/upload_resume/" + fnm [0]+ ""));
            }
            return fnm[0];
           
        }

here i have shown how to upload three files and create directory as well .
You can upload multiple files and create directory  how much you need.

System.Web.HttpException: 'HtmlSelect' cannot have children of type 'LiteralControl'.

System.Web.HttpException: 'HtmlSelect' cannot have children of type 'LiteralControl'.
System.Web.HttpException: 'HtmlSelect' cannot have children of type 'LiteralControl'.

if you are getting this type of error while executing on running your asp.net application

in c# or in vb.net you must know about real cause or from where this error is occurring.

lets.. reavel this now what i did i just took

<select>
<option>
some information
</option>

</select>

and added runat="server" at .aspx page .


<select size="1" name="region" id="region"  runat="server">

now if we  run its gives error System.Web.HttpException: 'HtmlSelect' cannot have children

of type 'LiteralControl'....
to remove this error and make your application work easily..just add form name in your

.aspx pahe and add then add this line of code to .cs page.

remove runat="server"
Request.Form["region"].ToString();
and try now hope its works..

Sunday 20 October 2013

Sql command set | DML(Data Manipulation language) | Insert | Update | Delete

Sql command set | DML(Data Manipulation language) | Insert | Update | Delete
What is DML?
"Sql command set".
1-> "DML(Data Manipulation language)".
DML includes select ,insert , update , delete .
Let's study all there functionality one by one.

Database names:Stud
Table Name:student

i> Select;
we use select to fetch data from table or we can say to get record from table
use stud
select * from student.
here we can apply condition also like using where clause.
select * from student  where id=234

ii>Insert :
to insert  new record  in respected table we use insert.
insert into student values ("enter records you want to insert").


iii>Update 
to done modification in existing record.
update table table_name set column_name name where clause.

iv>Delete:
to delete unwanted records from table.
delete from table_name where column_name =parameter;

sql command set | DDL(Data definition language). | create | Alter | Drop

sql command set | DDL(Data definition language). | create | Alter | Drop
"Sql command set".
1-> "DDL(Data definition language)".
DDL includes Create ,alter , drop,truncate , comment , rename.
Let's study all there functionality one by one.

i->Create
 Create used  to create new table and object.
or you can create many tables and objects.
examples.
to Create table.
Create table student
(
id int identity primary key,
name varchar(20),
roll_no int
)
ii->Alter
 Used  to modify structure of table and other object..
alter table student alter name varchar(100)
using this query we can change size of column .
alter table student add  fee int.

iii->drop
Drop is used to drop table or column of table or object.
alter table student drop column name.
drop table student.
drop database stud.
we can drop database also by using drop keyword or command.


iv->Truncate 
Truncate use to delete all data present in the table.
But not table structure means , table will be there but it won't show any of record.

Truncate table Table_name
Truncate table student.

v->Comments
to add comments in procedure.

sp_insertrecord --'1','abcval'


vi->Rename
to rename  single table or multiple table in same database.
to rename single or multiple column in same table.

sp_rename 'existtablename' ,'renamedtablename'
SP_RENAME 'student.roll_no' ,'roll'  --to rename column name

SP_RENAME 'student' ,'stud'

sql server 2005/2008 | primary key | Identity key | Auto increment

sql server 2005/2008 | primary key | Identity key | Auto increment
how to set identity by query in table .
while creating by query in sql server 2008-2005 if you want to add
primary key with identity then you need to add primary key with identity at same time.
or if  you have already added then alter that  column but need to take care of  it.
here i have shown how to add identity with primary key in sql server 2005 and sql server 2008.
db name is stud
and table name is student.

user stud
create table student
(
id int NOT NULL primary key identity ,
roll int not null,
name varchar(30) not null

)

Wednesday 9 October 2013

how to Fetch data from .aspx page to .cs or .vb page using javascript | Attribute.Add | Gridview_RowCommand |

In this article  I have shown how to retrieve or fetch data or value from .aspx page to .cs or .vb page .
I have used here c#. now there is two method to   fetch .aspx value from .aspx page to .cs page.
How to use Confirm box in asp.net.
1->Ajax
2->Javascript.
3-Javascript with Attribute.Add Property.
Now suppose i want to display confirm box and after that if user is saying
or clicking yes then execute function else  exit.
In here .cs page i have tried same functionality with GridView_rowcommand event.
suppose user want to delete clicked row from table or we can say grid.
what he will do, firstly he will click on delete link button  , actually i have taken linkbutton into the grid.
after clicking delete link button Confirm Box will appear (poped up)
then according to yes or cancel selection function will be execute.
consider user  has clicked delete link button then ..
((LinkButton)(row.FindControl("lnkbtndel"))).Attributes.Add("onclick", "javascript:return GetConfirmval();");

GetConfirmval() function will be called which is javascript function .
now comes to javascript..


 <script type ="text/javascript" >
    function GetConfirmval()
    {
    var value;
var val=confirm ("Are you sure want to delete selected record ");
   if (val==true )
   {
   document .getElementById ('<%=hdnEditdel.ClientID%>').value=1;
   }
    else
    {
    document .getElementById ('<%=hdnEditdel.ClientID%>').value=2;
    }
   
    }
    </script>

what i did here is , taken one hiddenfield  and assigned  different values according to requirement.
what happens when user click on yes on confirm box hiddenfield values will be set 1.
else 2.

now this  value we will use  .cs page .


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
   {
       LinkButton lnkbtn = (LinkButton)e.CommandSource ;
           GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;

if (hdnEditdel.Value==Convert.ToString ("1")) // if value 1 means user clicked yes on confirm box.
           {

               Response.Write("1");

               DataTable dt = (DataTable)(ViewState["NewFirstTable"]);//stored data
               dt.Rows.RemoveAt(row.RowIndex);
               GridView1.DataSource = dt;
               GridView1.DataBind();
           }
           else
           {
               Response.Write("2");

           }
           hdnEditdel.Value = "";
}


now here is one way but in this method user need to click twice on link button which i have already used on gridview.
so to avoid that issue what i did i just took  OnlientClick  event and  call javascript function over there.
because that is perfect.
<asp:LinkButton runat="server" ID="lnkbtndel" Text ="Delete" CommandName ="Del" OnClientClick ="return GetConfirmval()"></asp:LinkButton>
step->
1->To use attribute remove onclient click on link button .
2->To use onclient click remove attribute from  rowcommand.


Tuesday 8 October 2013

Temporary Table In Asp.Net | C# | Gridview Bind | Edit Delete In single Click

How to create temp table in  code behind and bind with Gridview control in asp.net.
In this article i have shown and given code to edit or display only those value from grid to respective text box on which row user will click.if he had clicked on 3rd row then all the data from third row will come up and  will display in respective control.
Steps-
1.Take viewstate to store first value as user will enter .
2.Take actual table (temporary table not linked with database no need any connection for this).
3.Take number of column as per requirement .
4.Take datarow  to add column in to datatable.
------------------------------------------------------------------------------------------------
Now here is code to create temporary table.
   private DataTable  ProConnection()
    {
        //ClsBusinessConnection objBus = new ClsBusinessConnection();
        //DataTable BindAllVal = objBus.DClsBusinessConnection();
        //gridtodisplaytempData.DataSource = BindAllVal;
        // gridtodisplaytempData.DataBind();

//above  4 line code need to  bind gridview with database  connectivity.
//but  currently if you don't have database and you need to do some gridview functionality //then you can create temporary table.
        DataTable temporarytableDt = new DataTable();
        if (ViewState["NewFirstTable"] == null)
        {  temporarytableDt.Columns.Add("Id");
            temporarytableDt.Columns.Add("Name", typeof(String));}
        else{
            temporarytableDt = (DataTable)(ViewState["NewFirstTable"]);}
        DataRow datarowvar = temporarytableDt.NewRow();
        datarowvar["Id"] = TxtFirstVal .Text;
        datarowvar["Name"] =TxtSecondVal .Text;
        temporarytableDt.Rows.Add(datarowvar);
        ViewState["NewFirstTable"] = temporarytableDt;
        gridtodisplaytempData.DataSource = temporarytableDt;
       gridtodisplaytempData.DataBind();
         return temporarytableDt;
    }
------------------------------------------------------------------------------------------
Now what i am goin to do is to take commandsource and NamingContainer so ,
i can get rowindex which has already edit and delete linkbutton,
to edit and delete the data from temporary table and bind to the grid again.
No Need to take two function for edit and delete just take rowcommand and use command name .
but for adding purpose we need to take add function because that is not inside the grid.

  public void gridtodisplaytempData_Click(object sender , System .EventArgs e)
   {
       ProConnection();
   }

->Dont forget to add edit event..
 protected void gridtodisplaytempData_RowEditing(object sender, GridViewEditEventArgs e)
   {}
  protected void gridtodisplaytempData_RowCommand(object sender, GridViewCommandEventArgs e)
   {
       LinkButton lnkbtn = (LinkButton)e.CommandSource ;
           GridViewRow row = (GridViewRow)lnkbtn.NamingContainer;
       if (e.CommandName == "Edit")
       {
           TxtFirstVal.Text = ((Label)(row.FindControl("lblId"))).Text;
           TxtSecondVal.Text = ((Label)(row.FindControl("lbltitle"))).Text;
       }
         
       else
       {

           DataTable dtnew = (DataTable)(ViewState["NewFirstTable"]);
           dtnew.Rows.RemoveAt(row.RowIndex);
gridtodisplaytempData.DataSource = dtnew;
gridtodisplaytempData.DataBind();
                                  }
   }

now when you click edit link button ..
if (e.CommandName == "Edit")
       {
         
           TxtFirstVal.Text = ((Label)(row.FindControl("lblId"))).Text;
           TxtSecondVal.Text = ((Label)(row.FindControl("lbltitle"))).Text;
       }

this code will get execute and for delete ..
  DataTable dtnew = (DataTable)(ViewState["NewFirstTable"]);
           dtnew.Rows.RemoveAt(row.RowIndex);
gridtodisplaytempData.DataSource = dtnew;
gridtodisplaytempData.DataBind();

it will take directly rowindex and will romove that row from temporary  table.
--------------------------------------------------------------------------------

    <div>
    <table >
 
    <tr><td>Enter Id:</td><td>:</td><td><asp:TextBox  runat="server" ID="TxtFirstVal"></asp:TextBox> </td></tr>
    <tr><td>Enter Name:</td><td>:</td><td><asp:TextBox  runat="server" ID="TxtSecondVal"></asp:TextBox> </td></tr>
    <tr>
    <td colspan ="3">
 
    <asp:Button runat="server" ID="btnSubmit" Text ="Submit"
            onclick="btnSubmit_Click" />
         
            <asp:Button runat="server" ID="btnAdd" Text ="Add" onclick="btnAdd_Click"/>
            <asp:label runat ="server" ID="lblnum" ></asp:label>
     
        <asp:GridView ID="gridtodisplaytempData" runat="server" AutoGenerateColumns ="false"
            GridLines="Both"  AllowSorting ="true" PageSize ="5"
         

            onrowcreated="gridtodisplaytempData_RowCreated"
 onrowediting="gridtodisplaytempData_RowEditing"  >
        <HeaderStyle/>
        <Columns >
        <asp:TemplateField  ><ItemTemplate >
        <asp:LinkButton runat="server" ID="lnkbtndel" Text ="Delete" CommandName ="Del"></asp:LinkButton>
        <asp:LinkButton runat="server" ID="lnkbtn"  Text ="Edit" CommandName ="Edit"></asp:LinkButton>
        <asp:label runat="server" id="lblId" SortExpression ="dt"  Text='<%#Eval("Id") %>'  HeaderText ="ID"

HeaderStyle-CssClass ="CssClass"></asp:label> </ItemTemplate></asp:TemplateField>
        <asp:TemplateField HeaderText ="Title" SortExpression ="UsrScrM_Title"><ItemTemplate >
        <asp:label runat="server" id="lbltitle"  Text='<%#Eval("Name") %>'  HeaderText ="ID"  HeaderStyle-CssClass

="CssClass"></asp:label> </ItemTemplate></asp:TemplateField>
     
   
        </Columns>
     
        </asp:GridView>
    </td>
    </tr>
    <tr><td>&nbsp;</td> </tr>
 
    </div>

Tuesday 4 June 2013

how to write Prime number logic in sql server 2008

how to write Prime number  logic in sql server 2008
In this program i am going to give you code how to write prime number in sql server 2008.
prime number divisible by itself and by one.that we call as prime number.
i have shown here using while and if loop to check whether given number is prime or not

ALTER procedure [dbo].[prime_number]
(@@val int)
as
begin
declare @int int;
set @int=2;
while(@int < @@val)
          begin
if (@@val % @int=0)
            begin
            set @int=9;
break;
         end
          else
       set @int=@int + 1;
end
if (@int=9)
begin
print 'number is not prime number'
end
else
print  'NUMBER is prime number'
end

Sunday 2 June 2013

delete record with checkbox checked event in gridview with code

delete  record with checkbox checked event in gridview with code
in this program i am going show you how to  delete record on checkbox changed event when you

have taken checkbox into gridview .
on check box checked record will be deleted.


    protected void chkval_CheckedChanged(object sender, EventArgs e)
    {

        CheckBox chk = (CheckBox)sender; //will make checked checkbox true
      
           GridViewRow row = (GridViewRow)chk.NamingContainer; //will hit row
            Boolean ischecked =((CheckBox)(row.FindControl("chkval"))).Checked ;
//will find  checkbox which has selected or checked
           if (ischecked)
            {
                txtnm.Text = ((Label)(row.FindControl("lblNm"))).Text;
                delete(txtnm.Text);
            }
            else
           {

           }
           bind();
    }


now check for delete function from  where we are passing value from checked event.

  public void delete(string nm)
    {
       con.Open();
       SqlCommand cmd = new SqlCommand("delete from  stud where nm='"+nm+"'", con);
       int i= cmd.ExecuteNonQuery();
       con.Close();
       if (i > 0)
       {
           string deletevalue = "<script>alert(record deleted succesfully);</script>";
      Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", deletevalue,false);
         
       }
       else
       {

       }
    }
now after click on checkbox value will be deleted from  respective table and database.

   <asp:GridView runat="server" ID="grd" AutoGenerateColumns ="false" >
    <Columns >
    <asp:TemplateField headertext ="Id">
    <ItemTemplate >
    <%#Eval("id")%></ItemTemplate>
    </asp:TemplateField>
      <asp:TemplateField headertext ="Name">
    <ItemTemplate >
   <asp:Label runat="server" ID="lblNm" Text='<%#Eval("nm")%>'></asp:Label></ItemTemplate>
    </asp:TemplateField>
      <asp:TemplateField headertext ="Select">
    <ItemTemplate >
    <%#Eval("lnm")%></ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField headertext ="Select">
    <ItemTemplate >
    <asp:CheckBox ID="chkval" runat="server" AutoPostBack="true" OnCheckedChanged="chkval_CheckedChanged" />
 </ItemTemplate>
    </asp:TemplateField>
   
       <asp:TemplateField headertext ="Lname">
    <ItemTemplate >
   <input type =text   id="txtAdd" value ='<%# "Mr  " +Eval("nm")+" "+ Eval("lnm") %>'/></ItemTemplate>
    </asp:TemplateField>
   
    </Columns>
    </asp:GridView>


   public void bind()
    {
        con.Open();
        SqlCommand cmd1 = new SqlCommand("select *  from stud", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd1);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        ViewState["viewds"] = ds;
        grd.DataSource = ds;
        grd.DataBind();
        con.Close();
    }

CheckedChanged | checkBox | notworking | gridview in c# | Solution

CheckedChanged | checkBox | notworking | gridview in c# | Solution

 just add

 if (!IsPostBack)
        {
            bind();
        }
        else
        {

        }


on page load it  will work .
here i have shown how to emb ed cheked changed event in gridview when you are using gridview .

inside the gridview
 <asp:TemplateField headertext ="Select">
    <ItemTemplate >
    <asp:CheckBox ID="chkval" runat="server" AutoPostBack="true" OnCheckedChanged="chkval_CheckedChanged" />
 </ItemTemplate>
    </asp:TemplateField>

protected void chkval_CheckedChanged(object sender, EventArgs e)
    { //your code
    }

Thursday 23 May 2013

how to draw pattern like 123 | if condition | without using loop | comments

  how to draw pattern like 123 | if  condition | without using loop | comments
   how to draw pattern like 123 | if  condition | without using loop
            1
            12
            123.

  simple program codes showing to draw 123 pattern. Logic is very simple just  divide value using 100 , 10, and 1I have shown here code and also out put of given program in c#
        int val = 123;
        int temp = 0;

        int last = 3;
        if(last>2)
        {
            temp = val / 100; //will gives 1 because 123/100 remainder will be 23
            Response.Write(temp);
            Response.Write("</br>");
            temp = val / 10; //will gives 12 because 123/10 remainder will be 3
            Response.Write(temp);
            Response.Write("</br>");
            temp = val / 1; ////will gives 123 because 123/1 remainder will be 0
            Response.Write(temp);
           
           // just simple funda  not a very difficult source code.

Wednesday 22 May 2013

How to revese number | integer in c# | examples code | comments

How to revese number | integer in c# | examples code | comments
In this article we are going to learn how to reverse a integer or numeric number in c#.
With help of for loop i have shown the program to reverse the given number.
Don't ignore comments.

        int temp = 0;  //took temporary variable
        int val =13298765; //passed  integer value to the integer type variable val
        for (int i=0; val>0 ;i++) // now  increment of i
        {
            temp =val % 10; // storing all the   single digit  in temp variable
            val =val/10; //taking remaining value after mod
            Response.Write(temp);
        }


In this program we don't need to take length because it won't works.
it works at time of sring and array.
mod [%] will give you last value on number.
and / will store remaining one in val variable.




output :-56789231



another example
 /int count = 34;
        int temp = 0;
        while (count > 0)
        {
            temp = count % 10;
            count = count / 10;
         Response.Write(temp);



     

How to reverse string in c# | asp.net | example | output

How to reverse string in c# | asp.net | example | output
reverse string using for loop in c#  with program source code.
         In this program we are going to learn how to reverse  a string using temporary variable and
        display them at last .a very simple process .take string calculate length of string using for loop
        count it till its last character.after display it .
        i have shown program with source code. and output also .


        string temp="";  //took temporary variable
        string str = "enteryourstring"; //passed string
        int last = str.Length; //calculated length of string
        for (int i =last -1;i>=0 ; i--) // now decrement
        {
            temp = temp + str[i]; // storing all the  character in temp variable
        }
        Response.Write(temp); //display

output:gnirtsruoyretne

Monday 8 April 2013

gridview rowcommand with insert | update | delete in c#

gridview rowcommand with insert | update | delete in c#
In this article we will learn how to use grid view rowcommand event to insert, update and delete the record in asp.net with c#

now for that i have created table named as usertbl. and took three field first one is id , name and company.
same way three text box .to insert the value into table.
4    rajana    nit
38    dev    lolo
45    dev    lolol



using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI.WebControls;



public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);


    protected void Page_Init(object sender, EventArgs e)
    {
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        display(); 

    }
    protected void btnsbmit_Click(object sender, EventArgs e) //for insertion
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert_db", con);
            cmd.CommandType = CommandType.StoredProcedure;
           
            cmd.Parameters.AddWithValue("@nm", txtnm.Text);
            cmd.Parameters.AddWithValue("@comp", txtcom .Text );
            cmd.ExecuteNonQuery();
            cmd.Dispose();
        }
        catch { }

        finally
        {
            con.Close();
           
        }

        display();

    }
    protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
    {



        if (e.CommandName == "select")
        {

            ViewState["val"] = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = (GridViewRow)(((LinkButton  )e.CommandSource).NamingContainer);
//taking gridview index so we can that row values.
            int selIndex = row.RowIndex;
            string last = grd.Rows[selIndex].Cells[2].Text;
            string comp = grd.Rows[selIndex].Cells[3].Text;
            txtnm.Text = last;
            txtcom.Text = comp;
         
      }
        if (e.CommandName =="del")
        {
            int del = Convert.ToInt32(e.CommandArgument);
            ViewState["val"] = del;
           SqlCommand cmd = new SqlCommand("delete from usertbl where id='" + del + "'", con);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                lblmsg.Text = "Record deleted succesfully";
            }
            catch { }
            finally
            {
                con.Close();
            }

            display();

           
        }

    }
    protected void btnupdate_Click(object sender, EventArgs e)
    {
        int i = 0;
        int last =Convert.ToInt32 ( ViewState["val"]);
        //string l1 = Replace(txtnm.Text, "", "-");
        string str = "update usertbl set name='" + txtnm .Text  + "', company ='" + txtcom .Text +"' where id='" + last + "'";
        con.Open();
        SqlCommand cndupdate = new SqlCommand(str, con);
        i=cndupdate.ExecuteNonQuery();
        if (i >= 1)
        {
            lblmsg.Text ="Record updated succesfully";
        }
        con.Close();
       
        display();

    }
    public  void  display()
    {
       
        DataSet ds = new DataSet();
        con.Open();
        SqlCommand cmd1 = new SqlCommand("select * from usertbl", con);
        SqlDataAdapter sda = new SqlDataAdapter(cmd1);
        sda.Fill(ds);
        ViewState["ds"] = ds;
        grd.DataSource = ds;
        grd.DataBind();
        con.Close();
    }

 
    protected void grd_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grd_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataSet  ds = new DataSet ();
        ds=(DataSet )(ViewState["ds"]);
       // DataView dv = new DataView(ViewState ["ds"]);
       
    }
}





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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   <table>
   <tr><td>
   <asp:Label runat="server" ID="lbl">name</asp:Label></td>
   <td><asp:TextBox runat="server" ID="txtnm"></asp:TextBox></td>
   </tr>
    <tr><td>
   <asp:Label runat="server" ID="Label1">Company</asp:Label></td>
   <td><asp:TextBox runat="server" ID="txtcom"></asp:TextBox></td>
   </tr>
  <tr><td><asp:Button runat="server" ID="btnsbmit" onclick="btnsbmit_Click"
          Text="Submit" /></td> <td>
      <asp:Button runat="server" ID="btnupdate"
          Text="update" onclick="btnupdate_Click" Visible="False" /><td></tr>
          <tr><td><asp:Label runat ="server" ID="lblmsg"></asp:Label></td></tr>
   </table>
   <asp:GridView ID="grd" runat="server" onrowcommand="grd_RowCommand"
            onsorting="grd_Sorting">
   <Columns >
  
   <asp:TemplateField HeaderText ="Edit"  >
   <ItemTemplate >
  
<asp:LinkButton ID="edit" CommandName ="select" runat ="server" Text ="Edit"  CommandArgument  ='<%# DataBinder.Eval(Container, "DataItem.id") %>' ></asp:LinkButton>
<asp:LinkButton ID="delete" CommandName ="del" runat ="server" Text ="delete"  CommandArgument ='<%#DataBinder.Eval(Container,"DataItem.id") %>'></asp:LinkButton>
  </ItemTemplate>
     </asp:TemplateField>
   </Columns>
   </asp:GridView>
  
    </div>
    </form>
</body>
</html>


name
Company



Editidnamecompany
Edit delete 4rajananit
Edit delete 38devlolo
Edit delete 45devlolol

Thursday 4 April 2013

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory

It is an error to use a section registered as   allowDefinition='MachineToApplication' beyond application level.  This error can be caused   by a virtual directory

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.
E:\project\myproject\web.config 68


solution :-
If you are getting error like this and after  running your application you are getting error
liker <authentication mode="Forms"/> so  i have Solution just check your project or website
which you have opened . may be there will another web.config file.
where you have pasted your application or website folder open only than folder don't open
sub folder .


Example you  want to open your primenumberprogram website ,means  primenumberprogram  is
your website folder and there is web.config file , you kept your primenumberprogram   folder
in mywebsite folder and you are opening mywebsite folder instead of primenumberprogram  
folder then you will get erro like It is an error to use a section registered as
allowDefinition='MachineToApplication' beyond application level.  This error can be caused
by a virtual directory not being configured as an application in IIS.

E:\project\myproject\web.config.

so check acccurately where you have kept your website and from where you are opening that folder.
hope it will work

Monday 1 April 2013

Maximum request length exceeded. | asp.net | vb.net

Maximum request length exceeded. | asp.net | vb.net

i am designing crystal report , for single or less record its working proper ,
means it is displaying proper but at time of
displaying lacs record at a time its showing error

Maximum request length exceeded. 

so what i did , i just pasted one line code and its started working fine.
how to paste that code and where .
go into web.config file and search for <system.web>
 paste

<httpRuntime maxRequestLength="1000000" />
brfore closing system.web

<system.web>

other code ----------------
---------------------------
<httpRuntime maxRequestLength="1000000" />
</system.web>

i am sure it will work.

About maxRequestLength i think it will related something if we are posting  huge data to
server and it cause , so to avoid we provide  length='1000000'
The value must be inside the range 0-2097151.

Wednesday 13 March 2013

Perfect Number | program for single number | 1 to 100 | in c# with source code | output

Perfect Number  | program for  single number | 1 to 100 | in c# with source code | output

Perfect Number  | single number | 1 to 100 | in c# with source code | output with explanation
In this program i have shown how to check whether entered number is perfect number or not.
Logic i have developed is so simple .Anyone can learn easily.
so first i will show you how to check perfect  number logic for single number.
Definition of perfect number:- Perfect number is number which is equal to  its factor's addition.
example 6 has 3 factor 3 and 2 and 1 now if i will add 1 +2+ 3=6 which is number itself.so , we can say
6 is perfect number.
now check for 8.
1,2,2,2 here if i will add 4 number i will get 1+2+2+2=7 which is not equal to 8.so, 8 is not perfect number.
Here is source code in c# .similar code we can write in c and other language just change the
printing syntax.

  protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("</br>");
        Response.Write("How to check The given number is Perfect number or not");
        Response.Write("</br>");
        Response.Write("----------------------------------------------------------");
        Response.Write("</br>");
        int num = 10;
        int sum = 0;
        for (int i = 1; i < num; i++)
        {
            if (num % i == 0) // finding its factor
            {
                sum = sum + i;
            }
        }
            if(sum==num)
            {
                Response.Write (num+ "is Perfect Number ");
            }
            else
            {
                Response.Write (num+ " is  Not Perfect Number ");

            }
       

    }


output:-
How to check The given number is Perfect number or not
----------------------------------------------------------
10 is Not Perfect Number


Now i want to print list of perfect number from 1 to 100 .
logic will be same just include one more for loop.




   protected void Page_Init(object sender, EventArgs e)
    {
        Response.Write("</br>");
        Response.Write ("Print List oF  perfect Number from 1 to 100");
        Response.Write("</br>");
        Response.Write("----------------------------------------------");
        Response.Write("</br>");
        int num = 100;
        int sum = 0;
        for (int j = num; j > 0;)
        {
            for (int i = 1; i < j; i++)
            {
                if (j % i == 0)
                {
                    sum = sum + i;

                }
               

            }
            if (j == sum)
            {
                Response.Write(j + " is Perfect Number");
                Response.Write("</br>");
            }
            j--;

            sum = 0;
           



        }

    }
     

output:-


Print List oF perfect Number from 1 to 100
----------------------------------------------
28 is Perfect Number
6 is Perfect Number

Tuesday 12 March 2013

Sum Of series in c#.net source code with output and explanation

Sum Of series in c#.net source code with output and explanation

Sum Of series in c#.net source code with output and explanation
in this program we will see how to calculate sum of series till sum number like 10 , 20 , etc....
Now what we will do we will just take two value assign them as 0  and 1. so , at least we will get
some value at start.
In this article i have shown here how  to calculate sum of series in c# .net on Page Init
 event.


 protected void Page_Init(object sender, EventArgs e)
    {
       
     
       int a=0;   //here i have initialize two valus as 0 and 1.
        int b=1;
        int num=20;
        Response.Write("Sum Of series Before:"+num);
        Response.Write("</br>");
       int  sum=0;
        for (int j=1;j<=num;j++)
        {
            sum=a+b; //swappping.............
            a=b;
            b=sum;
            Response.Write(sum+"-");  // printing the values.......
        }

       
        }


OUTPUT
Sum Of series Before:20
1-2-3-5-8-13-21-34-55-89-144-233-377-610-987-1597-2584-4181-6765-10946  

IF YOU WILL TAKE NUM=10
THEN OUTPUT WILL

Sum Of series Before:10
1-2-3-5-8-13-21-34-55-89 

Monday 11 March 2013

Factorial Number program source code | From 1 to n range | c#.net

  Factorial Number program source code | From 1 to n range | c#.net
  Factorial Number program source code | From 1 to n range | c#.net
In this program i have shown how to find factorial number of given range.
using for loop i have calculated factorial number from 1  to 5 .
But , we  can calculate factorial number from 1 to n using below given source code.
output is there.
same logic we  can apply in c language , vb.net also but difference is only of syntax will be changed.
rest logic will be same.

 protected void Page_Init(object sender, EventArgs e)
    {

        int sum = 1;
        int i = 5;

        for (int j = i; j > 0; )
        {

            for (int k = 1; k <= j; )
            {

                sum = sum * j;
                j--;
            }
            Response.Write("Factorial of " + i + "is" + "\t" + sum);
            Response.Write("</br>");
            i--;
            j = i;
            sum = 1;

        }
  
          
               }


Factorial of 5 is 120
Factorial of 4 is 24
Factorial of 3 is 6
Factorial of 2 is 2
Factorial of 1 is 1

Prime Number source code | C#.Net | Prime Number from 1 to n..with examples and comments

Prime Number source code | C#.Net | Prime Number from 1 to n..with examples and comments

 source code how to calculate prime number in c#.net.With valid and correct output.
Definition Of Prime Number:- The number which is divisible by 1 and itself.
or we can say prime number is a number which has only two factor first one is 1 and second
is that number itself.
 in this article i have shown to calculate prime number from one range to n range and also how to find
simple number  is prime or not.


Now first to calculate whether entered number is prime number or not.
here is code:- on page init


   
    protected void Page_init(object sender, EventArgs e)
    {
           
        int num=20, flag=0;
     
     
        for (int i=2;i<;num/2++)//i will be less than half of number it will also work.
        {
          if(num%i==0)
          {
          flag=1;   // now entered number 20 is divisible by 2 means 20 has another factor that is 2
so , it  is not prime number no need to go in execution use break statement.
          break;
         
          }
          else
          {
          flag=0;
          }
        }
        if (flag==0)
        {
          Response.Write(" +num+"is  not prime number :-");
        Response.Write("</br>");
        }
else
{

 Response.Write( +num+"is  a  prime number :-");
}

       
     


    }
}


It was simple program to check number is prime or not now i want to check number from n to n+...
or 1 to 20 , 1 to 100 , 1 to 1000 just enter num=100 or num=1000 as you want range.

   
    protected void Page_init(object sender, EventArgs e)
    {
           
        int num=20, flag=0;
        Response.Write("Prime Number from 2 to" +num+"is :-");
        Response.Write("</br>");
        for (int j=2;j<num;j++)
        {
        for (int i=2;i<j;i++)
        {
          if(j%i==0)
          {
          flag=1;
          break;
         
          }
          else
          {
          flag=0;
          }
        }
        if (flag==0)
        {
        Response.Write(j);
         Response.Write("</br>");
        }
       
        }


    }
}


Prime Number from 2 to 20 is :-
2
3
5
7
11
13
17
19



Wednesday 6 March 2013

How to store date value into viewstate in vb.net | c#.net.

How to store date value into viewstate in vb.net | c#.net.

How to store date value into viewstate in vb.net | c#.net with explanation and example in asp.net.
How to check whether viewstate is null or have some values.

It is very simple to store value and retrieve it on another place.
we can store datatable , simple variable in viewstate to fetch same data later
 on whenever we need to use that respective data.
so coming on point i am goinG to write code how to store date value or data time into viewstate and display it.

            ViewState("fromdate") = controlName1.SelectedDate
            ViewState("Todate") = controlName2.SelectedDate

NOW Here i am assigning data value into viewstate named  fromdate and todate.

in c#

    ViewState["fromdate"]= controlName1.SelectedDate
    ViewState["Todate"]= controlName2.SelectedDate

now i have store from date value and to date value into viewstate named as
fromdate and todate both are in doublw quotes.now i want to retrieve that same value into another function.
what i will do , i will just take control name and  assign viewstate value there.

 Dim lbl As New Label
 lbl.Text = CType(ViewState("frm"), Date)

so , label will display data value.


now in c# 
  lbl = New Label()
 lbl.Text = CType(ViewState["frm"], Date);


just change that bracket style.

so if you want to use same variable after postback use viewstate .
less burdon on server, because viewstate is client side state management.once page unloaded viewstate destroy.


after if you want to check whether viewstate  has value or not you can write code like this

  Dim lbl As New Label
            If ViewState("frm") = CType("12:00:00 AM", Date) Then
                lbl.Text = "something"
            Else
                lbl.Text = CType(ViewState("frm"), Date)
                Response.Write(lbl.Text)
            End If

Try it and implement it.



Tuesday 5 February 2013

Crystal Report viewer not showing(displaying) in toolbox visual studio 2005|2008.


How to add crystal Report viewer   in toolbox
when you are trying to add crystal report viewer in your .aspx form and if you are not getting
that module in toolbox simply do one thing.
Just right click on toolbox >add new tab -> write Reporting or whtever name you want to give your module.

step 1->right click on toolbox  new box will appear blank just give name to box.optin will appear add tab.
give any defalt tab name.



step2->right click on add given  tab name.and select choose item which you want to import.






NOW BOX WILL OPEN TO GIVE YOU MORE REFERENCES SO YOU CAN CHOOSE AS PER YOUR REQUIREMENT.
now here you will get reference of crystal report viewer to add in your toolbox.select all the reference which belongs or useful in designing of crystal report.
Now After all step just go  to your toolbox left side and check by clicking + sign .whatever name you had specified to crystal report tab.
now you can open your .aspx  page and drag report viewer from report tab  from toolbox.



Tuesday 8 January 2013

Image upload code in c# | asp.net image file uploading in database | gridview


How to upload images in asp.net using c#

string path = Server.MapPath("Images/"); //Images is folder here it will show full path where file or pic is going to store//

lblMessage.Text = path;

if (FileUpload1.HasFile)

{

string Filext = Path.GetExtension(FileUpload1.FileName);

if(Filext==".jpg" || Filext==".png")

{
 HttpPostedFile myFile = FileUpload1.PostedFile;
                int nFileLen = (myFile.ContentLength)/1000; // will check file length
FileUpload1.SaveAs(path+ FileUpload1.FileName);
string filnm="~/Images/"+FileUpload1.FileName;
string nm = txtName.Text.Trim();
string filenm = filnm.ToString();
string query="insert into images (ImageName,Image)values (@imgnm,@imgpath)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@imgnm", nm);
cmd.Parameters.AddWithValue("@imgpath", filenm);
SqlCommand disply = new SqlCommand("select * from images", con);
SqlDataAdapter da = new SqlDataAdapter(disply);
DataTable dt = new DataTable();
da.Fill(dt);
grdvw.DataSource = dt;
grdvw.DataBind();
con.Open();
int i = 0;
i= cmd.ExecuteNonQuery();
if(i>0)
{
lblMessage.Text="Image uploaded succesfully";
}
else
{
lblMessage.Text="Please select the image";
}
}
else
{
lblMessage.Text="please selest .png or .jpg files only";
} } }



<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="btnupload1" onclick="btnupload1_Click" runat="server" text="Upload">

<asp:textbox id="txtName" runat="server" width="95px">

</asp:textbox>
<asp:label id="lblMessage" runat="server"></asp:label>
<asp:gridview autogeneratecolumns="false" id="grdvw" runat="server">
<columns>
<asp:boundfield datafield="ID" headertext="Number">
<asp:boundfield datafield="ImageName" headertext="Product">
<asp:imagefield controlstyle-height="120px" controlstyle-width="120px" dataimageurlfield="Image" headertext="Image">
</asp:imagefield>
</asp:boundfield></asp:boundfield></columns>
</asp:gridview></asp:button></asp:fileupload></div>