Tuesday, 29 January 2013

What’s the difference between Response.Write() andResponse.Output.Write()...?

Response.Write() and Response.Output.Write() both are used for print output on the screen.
But their are is a difference between both of them

1. Response.Output.Write() is allows us to print formatted output but Response.Write() can't allows the formatted output.
Example:

Response.Output.Write(".Net{0},"ASP"); // Its write

Response.Write(".Net{0},"ASP"); // Its Wrong

2. As Per Asp.Net 3.5, Response.Write() Has 4 overloads, with Response.Output.Write()
has 17 overloads .

Tuesday, 22 January 2013

How to change one comboBox Items based on selection in another comboBox Item.

In this article iam going to explain how to change the combobox items on selection of another combobox.
Basically their are so many ways to solve this problem. but in this iam used simple way. I think it may be
helpful for beginners.
Drag and drop two Comboxes in windows form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace droupdown
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == "B.Tech")
            {
                comboBox2.Items.Add("IT");
                comboBox2.Items.Add("CSE");

            }
            else if (comboBox1.SelectedItem == "PG")
            {
                comboBox2.Items.Clear();
                comboBox2.Items.Add("MCA");
                comboBox2.Items.Add("MBA");
            }
            else
            {
                MessageBox.Show("select item");
            }
        }
    }
}

In this i took very less Items so it will work but what about for large number of items…? I will give solution for that one in ASP.Net. Thank You.

Monday, 21 January 2013

How to change The Timer time format in vb.net

In this article I am going to tell how to change the timer time format using string format. Conceptually this is simple. in practice there are some details you must account for if you want a functional program. Formatting your DateTime as a string is straightforward with an understanding of the syntax.

As we begin, please notice how the current DateTime is acquired through the DateTime.Now property. When you execute these code examples, the current DateTime will be different.
 
Exmaple:

12 Hours Format:

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System. 
EventArgs)  
Handles MyBase.Load
        Timer1 = New Timer
        Timer1.Interval = 1000

        Timer1.Start()
        
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As  
System.EventArgs
Handles Timer1.Tick
        Label1.Text = TimeOfDay

    End Sub

   
End Class

24 Hours format:

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As 
 System.EventArgs)  
Handles MyBase.Load
        
        Timer2 = New Timer
        Timer2.Interval = 1000
        Timer2.Start()
    End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As  
System.EventArgs)  
Handles Timer2.Tick
        Dim time As DateTime = DateTime.Now
        Dim format As String = "HH:mm:ss" ‘ this is using to define the string
format.
        Label2.Text = time.ToString(format)
    End Sub
End Class


Thursday, 17 January 2013

How To Update Gird View in Asp.Net

This article will give you an overview of how to use an asp:GridView completely, and how to use RowEditing,RowUpdating, RowDeleting, RowCommandRowCancelingEdit, and Pagination in a DataGrid. From this article, you will have a clear view of the GridView data  delete, and update operations.

Create Sql Table:
Create Table Employee
(
ID int,
Firstname nvarchar(50),
Lastname nvarchar(50),
DateOfBirth nvarchar(50),
JobTitle nvarchar(50),
Location nvarchar(50),
EmailAddress nvarchar(50)
)

Web.Config Connection string:

<connectionStrings>
  <add name="myconnectionstring" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=
|DataDirectory|\srujan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

 
Design  page:  

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Employee1.aspx.cs" Inherits="employdetails.Employee1" %>
<!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 style="font-weight: 700; color: #000066">
  <asp:Table ID="formtable" runat="server" HorizontalAlign="Center" Caption=" EMPLOYEE FORM" >
 <asp:TableRow >
  <asp:TableCell>
     EmpID
  </asp:TableCell>
  <asp:TableCell>
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  FirstName
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  LastName
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  DateOfBirth
  </asp:TableCell>
  <asp:TableCell>
 <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
   JobTitle
  </asp:TableCell>
  <asp:TableCell>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
    Location
  </asp:TableCell>
  <asp:TableCell>
 <asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
  

<asp:TableRow >
  <asp:TableCell>
  EmailAddress
  </asp:TableCell>
  <asp:TableCell>
  <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
  </asp:TableCell>
  </asp:TableRow>
     

 <asp:TableRow>
 <asp:TableCell>
</asp:TableCell>
      <asp:TableCell>
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
      </asp:TableCell>
      </asp:TableRow> 
    </asp:Table>
            <br />
            <br />
            <br />
        <br />
        <%-- GridView start from here --%>  
<asp:GridView ID="Gridview1" HorizontalAlign="Center" runat="server"
 AutoGenerateColumns="false" OnRowCancelingEdit="GridView1_RowCancelingEdit" 
DataKeyNames="ID,Firstname" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"OnRowDeleting="GridView1_RowDeleting">
 
 <%-- Header Of Grid View --%> 
<HeaderStyle BackColor="Blue" ForeColor="White" HorizontalAlign="Left"
 Height="20" />
 
 <%-- Grid View columns ID, Firstname, Lastname, DateofBirth, JobTitle, Location, 
EmailAddress --%>            
<Columns>
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true"  
ShowCancelButton="true"ButtonType="Button" />

                    <%-- We con't Edit this BoundField --%>

<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="Firstname">
<ItemTemplate><%# Eval ("Firstname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textFirstname" Text='<%#Eval("Firstname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
                
<asp:TemplateField HeaderText="Lastname">
<ItemTemplate><%#Eval ("Lastname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textLastname" Text='<%#Eval("Lastname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
<asp:TemplateField HeaderText="DateOfBirth">
<ItemTemplate><%#Eval("DateOfBirth")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textDateOfBirth" Text='<%#Eval("DateOfBirth") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
<asp:TemplateField HeaderText="JobTitle">
<ItemTemplate><%#Eval("JobTitle")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textJobTitle" Text='<%#Eval("JobTitle") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
               
               
               
<asp:TemplateField HeaderText="Location">
<ItemTemplate><%#Eval("Location")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textLocation" Text='<%#Eval("Location") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
                
                
                
<asp:TemplateField HeaderText="EmailAddress">
<ItemTemplate><%#Eval("EmailAddress")%></ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="textEmailAddress" Text='<%#Eval("EmailAddress") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
    </form>
</body>
</html>
 
 

Code Behind:


 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using System.Configuration;

namespace employdetails
{
    public partial class Employee1 : System.Web.UI.Page
    {
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                bind();
            }
        }

        
 
protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
con.Open();
SqlCommand cmm = new SqlCommand("insert into Employee values(" + Convert.ToInt32
(TextBox1.Text) + ", '" + TextBox2.Text + "', '" + TextBox3.Text + "', '"  
+ TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '"  
+ TextBox7.Text + "')",con);
cmm.ExecuteNonQuery();
bind();
        }
 
// data bind method
        public void bind()
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from Employee", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
            con.Close();
        }
       
// selecting a row index for editing 
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Gridview1.EditIndex = e.NewEditIndex;
            bind();
        }
 
// Row Editing Canceling Event
 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            Gridview1.EditIndex = -1;
            bind();
        }
 
// Row Updating Event
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = Gridview1.Rows[e.RowIndex];
            TextBox textFirstname = (TextBox)row.FindControl("textFirstname");
            TextBox textLastname = (TextBox)row.FindControl("textLastname");
            TextBox textDateOfBirth = (TextBox)row.FindControl("textDateOfBirth");
            TextBox textLocation = (TextBox)row.FindControl("textLocation");
            TextBox textJobTitle = (TextBox)row.FindControl("textJobTitle");
            TextBox textEmailAddress = (TextBox)row.FindControl("textEmailAddress");
            int ID = Int32.Parse(Gridview1.DataKeys[e.RowIndex].Value.ToString());
            string Firstname = textFirstname.Text.ToString();
            string Lastname = textLastname.Text.ToString();
            string DateOfBirth = textDateOfBirth.Text.ToString();
            string JobTitle = textJobTitle.Text.ToString();
            string Location = textLocation.Text.ToString();
            string EmailAddress = textEmailAddress.Text.ToString();
            updatedetails(ID, Firstname, Lastname, DateOfBirth, JobTitle, 
Location, EmailAddress); 
// calling a update method
        }
//updatedetails method definition  
        public void updatedetails(int ID, string Firstname, string Lastname,  
string DateOfBirth, string JobTitle, string Location, string EmailAddress)
        {
string query = "UPDATE Employee SET Firstname = @Firstname, Lastname=@Lastname, 
DateOfBirth=@DateOfBirth, JobTitle=@JobTitle, Location=@Location, 
EmailAddress=@EmailAddress WHERE ID = @ID";
                SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
                con.Open();
                SqlCommand com = new SqlCommand(query, con);
                com.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
                com.Parameters.Add("@Firstname", SqlDbType.VarChar).Value = Firstname;
                com.Parameters.Add("@Lastname", SqlDbType.VarChar).Value = Lastname;
                com.Parameters.Add("@DateOfBirth", SqlDbType.VarChar).Value = DateOfBirth;
                com.Parameters.Add("@JobTitle", SqlDbType.VarChar).Value = JobTitle;
                com.Parameters.Add("@Location", SqlDbType.VarChar).Value = Location;
                com.Parameters.Add("@EmailAddress",SqlDbType.VarChar).Value = EmailAddress;
                com.ExecuteNonQuery();
                Gridview1.EditIndex = -1;
                bind();
            
            
        }
        
// row deleting Event:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["myconnectionstring"].ConnectionString);
            con.Open();
            int ID = Int32.Parse(Gridview1.DataKeys[e.RowIndex].Value.ToString()); 
            string Firstname = Gridview1.DataKeys[e.RowIndex].Values["Firstname"].ToString();
           
            SqlCommand cmd = new SqlCommand("delete from Employee where ID=" + ID+ " and 
Firstname=Firstname", con);
            int result = cmd.ExecuteNonQuery();
            bind();
            con.Close();
        }
    }
}






 

Thursday, 10 January 2013

How to edit form authentication Credentials in web.conig

Add Namespaces:


using System.Web.Configuration;
using System.Configuration;

web.config code:

<system.web>
<compilation debug="true">
</compilation>
<authentication mode="Forms">
<forms loginUrl="Default.aspx" defaultUrl="http://www.google.com/">
<credentials passwordFormat="Clear">
<user name="raghu" password="dayakar" />
</credentials>
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>


Design Code:

<body>
<form id="form1" runat="server">
<div>
<br />
Enter Your Old Name:   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
Enter Your New Name:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
Enter Your  New Pasword: <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
</div>
</form>
</body>

Code Behind Code:

protected void Button1_Click(object sender, EventArgs e)
        {
            Configuration webconfig = WebConfigurationManager.OpenWebConfiguration("~");

SystemWebSectionGroup sysweb = (SystemWebSectionGroup)webconfig.GetSectionGroup("system.web");

AuthenticationSection authSection = sysweb.Authentication;

FormsAuthenticationUserCollection users = authSection.Forms.Credentials.Users;
FormsAuthenticationUser user = users[TextBox1.Text]; 
user.Name = TextBox2.Text.ToString();
user.Password = TextBox3.Text.ToString();


webconfig.Save();
Response.Write("<script> alert(' sucessully updated') </script>");
        }


Monday, 7 January 2013

How to update GridView row in asp.net using c#

Step 1:
  Create a table items with the fallowing columns

create table items
(
iterm_no int,
name varChar(50),
price decimal
)

Step 2:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="srinivasgridview.aspx.cs" Inherits="gridview.srinivasgridview" %>

<!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:GridView ID="Gridview1"  runat ="server" AutoGenerateColumns ="false"
            OnRowCancelingEdit ="GridView1_RowCancelingEdit"  DataKeyNames ="iterm_no"
             OnRowEditing ="GridView1_RowEditing" OnRowUpdating ="GridView1_RowUpdating"
             >
            <HeaderStyle BackColor ="Gray" ForeColor="White" HorizontalAlign ="Left" Height="20" />
            <Columns >
            <asp:CommandField ShowEditButton ="true" ShowCancelButton="true" ButtonType="Button" />
            <asp:BoundField DataField ="iterm_no" HeaderText="ITEM_NO" ReadOnly ="true" />
            <asp:TemplateField HeaderText="Product Name" >
            <ItemTemplate >
            <%# Eval ("name") %>
            </ItemTemplate>
            <EditItemTemplate >
            <asp:TextBox runat ="server" ID="textname" Text ='<%#Eval("name") %>'>
            </asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Price" >
            <ItemTemplate >
            <%#Eval ("price") %>
            </ItemTemplate>
            <EditItemTemplate >
            <asp:TextBox runat ="server" ID ="pricetext" Text='<%#Eval("price") %>'>
            </asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            </Columns>
 
   </asp:GridView>
</div>
 </form>
</body>
</html>

Step 3: Set connection string in web.config File:

<connectionStrings  >
    <add name ="mycon" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\gridviewdatabase.mdf;Integrated Security=True;User Instance=True"/>
  </connectionStrings>

Step 4:
 Code behind code: 

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;

namespace gridview
{
public partial class srinivasgridview : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
{
 if (!Page.IsPostBack)
{
bind();
 }
}
public void bind()
 {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings ["mycon"].ConnectionString );
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from items", con);
DataTable dt = new DataTable();
 da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Gridview1.EditIndex = e.NewEditIndex;
bind();
}
 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
 e.Cancel = true;
 Gridview1.EditIndex = -1;
bind();
 }
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = Gridview1.Rows[e.RowIndex];
TextBox textname = (TextBox)row.FindControl("textname");
TextBox pricetext = (TextBox )row.FindControl("pricetext");
int item_no = Int32.Parse(Gridview1.DataKeys[e.RowIndex].Value.ToString());
string name = textname.Text.ToString();
 decimal Price = decimal.Parse(pricetext.Text);
 updateitems(item_no,name, Price );
}
public void updateitems(int item_no, string name, decimal Price)
{
 try
{
 string query = "UPDATE items SET name = @name, price = @price WHERE iterm_no = @iterm_no";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mycon"].ConnectionString);
 con.Open();
 SqlCommand com = new SqlCommand(query, con);
 com.Parameters.Add("@iterm_no", SqlDbType.Int ).Value = item_no ;
 com.Parameters.Add("@name", SqlDbType.VarChar ).Value = name;
com.Parameters.Add("@price", SqlDbType.Decimal ).Value = Price;
 com.ExecuteNonQuery();
 Gridview1.EditIndex = -1;
 bind ();
 }
 catch (Exception ex)
{
Response.Write("<script> alert('Error accrued')</script>");
 }
 }
}
}

Sunday, 6 January 2013

How to get connections string from web.config in Asp.Net

Set connection string in web.config file as below:

<connectionStrings >
 <add name ="connectiontodatabase" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

for retrieving Connection String from web.config write as

Add System.Data.SqlClient and System.Configuration references to Your code. 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;

namespace WebApplication2
{
 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
 protected void authenticationbutton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection  ( ConfigurationManager.ConnectionStrings ["connectiontodatabase"].ConnectionString );
 con.Open();
Response.Write("<script> alert('Connection opend') </script>");
con.Close ();
}
}
}

Saturday, 5 January 2013

What is the Difference Between Xml and Sql Data Storage.


In XML data storage, the data is stored in a file which represents
an XML Schema of the data. To read the data, you have to pull and
open the entire file in memory and use technics like xpath to get
the data element you want.

In SQL data storage, the data is stored in a database ( usually
relational database). To read the data, you simple sent an SQL query
to the database. The database management engine analysis the query
and get the required data elements you ask for in your query which
is finally sent to you as a reply.



"XML is not a database. It was never meant to be a database.
It is never going to be a database. Relational databases
are proven technology with more than 20 years of implementation
experience. They are solid, stable, useful products. They are
not going away. XML is a very useful technology for moving data
between different databases or between databases and other programs.
However, it is not itself a database. Don't use it like one."