Wednesday, September 1, 2010

Page Life Cycle of an ASP.NET

The life cycle starts when a user requests a web page through his/her browser. The Web server than process the page through a sequence of steps before response is sent back to the user's browser. The steps are as:

1. Page Request
2. Start
3. Page Initialization
4. Load
5. Validation
6. PostBack Event Handling
7. Render
8. Unload

Page Request
The page request occurs before the page life cycle begins. When a user requests the page, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page Initialization
During page initialization, controls on the page are available and each control's UniqueID are generated but not their properties. Any themes are also applied to the page.

Developers have access to the Init, InitComplete and PreLoad methods in this stage. The methods are as follows:

* Init: This event is raised after all controls have been initialized and any skin settings have been applied. This event is used to read or initialize control properties.
* InitComplete: The Page object raises this event. This event is used for processing tasks that require completion of all initialization.
* PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. The OnLoad event method is fired during this stage.
This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

PostBack Event Handling
If the request is a postback, any event handlers are called. The event handling for server controls occurs during this stage.

Render
During rendering, view state is saved to the page and then the page calls on each control to contribute its rendered output to the OutputStream of the page's Response property. Render is not really an event. The HTML of the page and all controls are sent to the browser for rendering.

Unload
Unload is called when the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed. The cleanup includes routines such as closing database connections and file streams, or, event logging and other tasks.

Conclusion
When a Web page is requested, the server creates objects associated with the page and all of its child controls objects and uses these to render the page to the browser. Once the final stage is complete, the web server destroys these objects, to free up resource to handle additional request.

Insert record in database using stored procedure in asp.net

In this article am explaining very simpe thing insert record in database using stored procedure,that will very help full for entry level programmer.

web.config
 <connectionStrings>  
<add name="conString" connectionString="Data Source=.\SQLEXPRESS; database=Northwind;Integrated Security=true"/>:
</connectionStrings>


Used Stored procedure
CREATE PROCEDURE [dbo].[AddUser]
(
@FName varchar(50),
@LName varchar(50),
@DateOfBirth datetime,
@City varchar(50),
@State varchar(50)
)
AS
BEGIN

SET NOCOUNT ON;
INSERT INTO UserDetails (FName, LName, DateOfBirth, City, State)
VALUES (@FName, @LName, @DateOfBirth, @City, @State)
END


C# code

 String ConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;  
SqlConnection con = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "AddUser";
cmd.Parameters.Add("@FName",SqlDbType.VarChar).Value = txtFName.Text.Trim();
cmd.Parameters.Add("@LName", SqlDbType.VarChar).Value = txtLName.Text.Trim();
cmd.Parameters.Add("@DateOfBirth", SqlDbType.DateTime).Value = txtDOB.Text.Trim();
cmd.Parameters.Add("@City", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("@State", SqlDbType.VarChar).Value = txtState.Text.Trim();
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
lblMessage.Text = "Record inserted successfully";
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}

Tuesday, August 31, 2010

Website Deployment

Internet Information Services is used to make your computer a web server. If we want to have a web server for developing dynamic website or want to publish
website on our own server then we install the IIS.Internet Information Server (IIS) is a World Wide Web server, a Gopher server and an FTP server all rolled
into one. IIS means that you can publish WWW pages.
If you want to your web application accessible to any other pc in intranet or internet you need to IIS.

Below are steps for deployment:
1.Right click your website and click on Publish website.All compiles files are ready for deployment.
2.Create a backup for database whichever you are using and restore it on production server.
3.Go to server using ftp or filezila copy all compiles file on server.
4.Open Webconfig and change the connection string according to your Database name and server.
5.Create a virtual directory for this website.
6.Your website is ready.
7.Test website http://192.163.0.234(ServerName)/VDName/Login.aspx

Thanks & Regards
Santosh

Difference Between .net framework 2.0,3.0 and 3.5

NET framework 2.0:

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework


.NET framework 3.0:

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website


.NET framework 3.5:

It implement Linq evolution in language. So we have the folowing evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.

Sunday, August 29, 2010

String Manupulation

i have a string like "a,b,c. upto n values"..
Show this string like
a,
b,
C

Sol
string str = "a,b,c";
string[] arr = str.Split(',');
foreach (string s in arr)
{
Response.Write(s + ",
");
}

Saturday, August 28, 2010

GridView Edit:on clicking edit a new page should be open where user can update data

 GridView Edit:on clicking edit a new page should be open where user can update data  
 On clicking edit in GridView a new page should be open where user can update data. In this article i am explaining how to update record using GridView.When User Click edit button in GridView new page will be open where user can update record.in second page i have just find the data not wrriten the code for update.  
 Here also i have written code for delete record in GridView and if GridView has no record show message no record found.  
 First Page code  
 public void GridViewBind()  
 {  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           DataSet ds = SqlHelper.ExecuteDataset(conn, "LeaveMaster_Select");  
           GridView1.DataSource = ds.Tables[0];  
           GridView1.DataBind();  
      }  
 }  
 protected void ImgDelete_Click(object sender, ImageClickEventArgs e)  
 {  
      ImageButton img = (ImageButton)sender;  
      Label Leave = img.FindControl("Label1") as Label;  
      using (SqlConnection conn = new SqlConnection(conStr))  
      {  
           conn.Open();  
           using (SqlTransaction t = conn.BeginTransaction())  
           {  
                try  
                {  
                     exceptionMessage.Text = SqlHelper.ExecuteScalar(t, "LeaveMaster_Delete", Leave.Text, "", 'D').ToString();  
                     t.Commit();   
                     GridViewBind();  
                }  
                catch  
                {  
                     t.Rollback();  
                }  
           }  
           conn.Close();  
      }  
 }   
 protected void ImgbtnDetails_Click(object sender, ImageClickEventArgs e)  
 {  
      //Selecting a Record from Grid For Updation..  
      ImageButton aspSender = sender as ImageButton;  
      Label lblId = aspSender.FindControl("lblLeaveID") as Label;  
      Response.Redirect("~/LeaveDetails.aspx?Id=" + lblId.Text + "");   
 }  
 ===========  
 2nd page  
 if (Request.QueryString["Id"] != null)  
 {  
      Id = Convert.ToInt32(Request.QueryString["Id"].ToString());  
      string str = "SELECT LeaveCode, LeaveDesc, LeaveId FROM LeaveMaster WHERE (LeaveId = "+Id+")";  
      DataTable dt1 = SqlHelper.ExecuteDataset(conStr, CommandType.Text, str).Tables[0];  
      txtCode.Text = dt1.Rows[0]["LeaveCode"].ToString();  
      txtCode.Enabled = false;  
      txtShortName.Text = dt1.Rows[0]["LeaveDesc"].ToString();  
      txtShortName.Enabled = false;   
 }  
 aspx Page  
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="LeaveId" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"   
 Width="700px" PageSize="10" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" >  
      <Columns>  
           <asp:TemplateField HeaderText="LeaveId" InsertVisible="False" SortExpression="LeaveId" Visible="False">  
                <EditItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("LeaveId") %>'></asp:Label>  
                </EditItemTemplate>  
                <ItemTemplate>  
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("LeaveId") %>'></asp:Label>  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:BoundField DataField="LeaveCode" HeaderText="Leave Code" SortExpression="LeaveCode" />  
           <asp:BoundField DataField="LeaveShortDesc" HeaderText="Short Desc" SortExpression="LeaveShortDesc" />  
           <asp:BoundField DataField="LeaveLongDesc" HeaderText="Long Desc" SortExpression="LeaveLongDesc" />  
           <asp:CommandField ButtonType="Image" HeaderText="Edit" SelectImageUrl="~/Image/img_edit.png" ShowSelectButton="True">  
           <ItemStyle HorizontalAlign="Center" />  
           </asp:CommandField>  
           <asp:TemplateField HeaderText="Details">  
                <EditItemTemplate>  
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                </EditItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="40px" />  
                <ItemTemplate>  
                <asp:ImageButton ID="ImgbtnDetails" runat="server"   
                OnClick="ImgbtnDetails_Click" />  
                </ItemTemplate>  
           </asp:TemplateField>  
           <asp:TemplateField HeaderText="Delete">  
                <ItemTemplate>  
                <asp:ImageButton ID="imgbtnDelete" runat="server"   
                OnClick="ImgDelete_Click" OnClientClick="return ConfirmDelete();" />  
                </ItemTemplate>  
                <ItemStyle HorizontalAlign="Center" Width="50px" />  
           </asp:TemplateField>  
      </Columns>  
      <EmptyDataTemplate>No record found !</EmptyDataTemplate>  
 </asp:GridView>  

Friday, August 27, 2010

Send mail using asp.net c# code

Send mail using asp.net c# code
This code describe how to send mail where mail id is stored in database and mail sender detail From,To,are stored in web.config file.Mail body can be customized according to requirement as described in code.

 public void MailSend()  
{
try
{
string mailToAdd = String.Empty;
MailMessage message1 = new MailMessage();
string strMail;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["SqlConnString"]);
SqlDataReader dr;
conn.Open();
SqlCommand cmd = new SqlCommand("usp_MediaRegistration", conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
strMail = (string)dr["emailID"];
message1.IsBodyHtml = true;
string MailFrom = ConfigurationManager.AppSettings["from"].ToString();
message1.From = new MailAddress(MailFrom);
message1.To.Add(new MailAddress(strMail).ToString());
message1.Subject = "Headline of the press release";
if (Request.QueryString["strmail"] == "0")
{
message1.Body = "<html><body><table><tr><td>Dear Users,</td></tr><br/>" +
"<tr><td><t/>This is to inform you that ...your message. <br/>" +
"<tr><td><t/>Please click on the link to see details....: <br/>" +
"<tr><td><a href='" + "http://xyz.com/mediapage.aspx?year=" + drlMyyyy.SelectedItem.Value
+ "'>" + "http://xyz.com/mediapage.aspx?year=" + drddMyyyy.SelectedItem.Value +
"</a></td></tr><br/>" +
"<tr><td>Thanks & Reagrds,</td></tr>" +
"<tr><td>santosh singh</td></tr> </table></body></html>";
}
}
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SmtpHost"]);
client.Send(message1);
}
catch (Exception ex)
{
string str1 = string.Format("Message Sending Fail Due To {0}.", ex.Message);
}
}


Thanks & Regards
Santosh Singh

Wednesday, August 25, 2010

Resize image in ASP.NET

In this example i am going to describe how to resize image in ASP.NET before/and upload to ms sql database using C# and Vb.NET.

For this i am using FileUpload control to upload the image in datbase after resizing.
I am also displaying the Image in Gridviw after uploading to database.

 public partial class _Default : System.Web.UI.Page   
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strImageName = txtName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
string strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
{
// Resize Image Before Uploading to DataBase
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 240;
int maxWidth = 320;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
UploadedImage.Value = image;
cmd.Parameters.Add(UploadedImage);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
GridView1.DataBind();
}
}
}
}


aspx code
 <form id="form1" runat="server">  
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" />
<asp:Label ID="lblMessage" runat="server"</asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [Images]">
</asp:SqlDataSource>
</form>


Thanks & Regards
Santosh

Tuesday, August 24, 2010

ViewState And Session example

Hi,

View state is used for store data at page level,you cant access View state data to another page.
Session state is used for store data and you can access anywhere in your website.
Session state is state specific information per client basis.

Example is given below.

View State:
 protected void btnSubmit_Click(object sender, EventArgs e)  
{
ViewState["DataScorceName"] = datasource;
ViewState["ClientName"] = txtCustomer.Text;
}
//Retrieve viewstate information
txtCname.Text = ViewState["ClientName"]
Store information in Session State:
Session["EmpName"] = txtUser.Text;
//Retrieve session value in 2nd page
lblEmp.Text = Session["UserName"].ToString();


Thanks & Regards
Santosh Singh

How to create connection string dynamically

Here i am using viewstate to create connection string at run time.
 protected void btnSubmit_Click(object sender, EventArgs e)  
{
ViewState["DataScorceName"] = datasource;
ViewState["Customer"] = txtCustomer.Text;
}
public void MyFunction()
{
string sqlConnectionString = "Persist Security Info=True;User ID=sa;Password=Sa;Initial Catalog=" + DBName + ";Data Source='" + ViewState["DataScorceName"] + "'";
}

How to reverse a string

 char [] myArray = txtName.Text.ToCharArray();  
Array.Reverse( myArray );
string strReversed = new string( myArray );
lblName.Text = strReversed;

how to use Sql server Function

Sql server Function With Arguments

here it is simple example how to use function n sql server.
1.Create function
2.use this function where required.

CREATE FUNCTION AddTwoNumber(@Num1 Decimal(6,2),
@Num2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Num1 + @Num2
RETURN @Result
END;
GO


PRINT MyDbName.dbo.AddTwoNumber(100, 200);

Sp for Creating db

Stored procedure for creating database.
When you want to create database at run time using c# .net here is stored procedure execute this and pass database name as parameter.

Create proc [dbo].[usp_Database]
(
@dbName varchar(50)
)
as

IF NOT EXISTS (SELECT 'True' FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME = @dbName)
-- DROP DATABASE ' + @dbName + '

DECLARE @device_directory NVARCHAR(520)
SELECT @device_directory = SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1)
FROM sys.database_files
WHERE (name = N'master')

EXECUTE (N'CREATE DATABASE ' + @dbName + '
ON
(NAME = ' + @dbName + ',
FILENAME = ''' + @device_directory + '' + @dbName + '.mdf'',
SIZE = 50MB,
MAXSIZE = 125MB,
FILEGROWTH = 10MB)
LOG ON
(NAME = ''NorthwindBulkLog'',
FILENAME = ''' + @device_directory + '' + @dbName + '.ldf'',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB)')

SetFocus to TextBox in GridView control

How to set focus in a GridView

Set Focus to TextBox in GridView when click on Edit Some time we have requirement to set focus in gridview,so here i am describing to how to this.
Drag and drop a gridview and bind it according to below code.

 protected void GridViewBind()  
{
try
{
Ds = obBLLclass.GetData();
if (Ds.Tables[0].Rows.Count > 0)
{
gridview.DataSource = Ds;
gridview.DataBind();
}
}
catch (Exception ex)
{
Message.Text = ex.Message;
}
}
protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
gridview.EditIndex = e.NewEditIndex;
GridViewBind();
gridview.Rows[e.NewEditIndex].FindControl("txtname").Focus();
}
protected void gridview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridview.PageIndex = e.NewPageIndex;
GridViewBind();
}


Thanks & Regards
Santosh Singh

How to insert excel file into sql database in ASP.NET

Import EXCEL sheet data to SQL Database table in ASP.NET
Here I will explain how to read excel file data and insert into in sql server database.

 protected void btnupload_Click(object sender, EventArgs e)   
{
String excelConnectionString1;
String fname = sendupload.PostedFile.FileName;
if (sendupload.PostedFile.FileName.EndsWith(".xls"))
{
String excelsheet;
sendupload.SaveAs(Server.MapPath("~/Image/" + sendupload.FileName));
if (sendupload.PostedFile.FileName.EndsWith(".xls"))
{
excelConnectionString1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/ExcelFiles/" + sendupload.FileName) + ";Extended Properties=Excel 8.0";
OleDbConnection myEcelConnection1 = new OleDbConnection(excelConnectionString1);
myEcelConnection1.Open();
if (txtsheet.Text.Length == 0)
{
lblmsg.Text = "Please Write File Name";
}
else
{
excelsheet = "[" + txtsheet.Text + "$" + "]";
string sheet = "Select * from [" + txtsheet.Text + "$" + "]";
OleDbCommand cmd1 = new OleDbCommand(sheet, myEcelConnection1);
cmd1.CommandType = CommandType.Text;
OleDbDataAdapter myAdapter1 = new OleDbDataAdapter(cmd1);
DataSet myDataSet1 = new DataSet();
myAdapter1.Fill(myDataSet1);
int a = myDataSet1.Tables[0].Rows.Count - 1;
string name;
string id;
string cls;
string num;
for (int i = 0; i <= a; i++)
{
name = myDataSet1.Tables[0].Rows[i].ItemArray[0].ToString();
id = myDataSet1.Tables[0].Rows[i].ItemArray[1].ToString();
cls = myDataSet1.Tables[0].Rows[i].ItemArray[2].ToString();
num = myDataSet1.Tables[0].Rows[i].ItemArray[3].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand command = new SqlCommand("Insert into StudentDetails(StudentName,CivilIdNumber,Class,StudentID)values(@valname,@valids,@valcls,@valnum)", con);
command.Parameters.Add("@valname", SqlDbType.VarChar, 50).Value = name;
command.Parameters.Add("@valids", SqlDbType.VarChar, 50).Value = id;
command.Parameters.Add("@valcls", SqlDbType.VarChar, 50).Value = cls;
command.Parameters.Add("@valnum", SqlDbType.VarChar, 50).Value = num;
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
}
}
}
}

.aspx page
 <table width="100%">   
<tr>
<td colspan="3"> <span style="font-family: Segoe UI"> File Upload</span> </td>
</tr>
<tr>
<td colspan="3">
<asp:FileUpload ID="sendupload" runat="server" /> </td>
</tr>
<tr>
<td colspan="3">
<span style="font-family: Segoe UI"> Sheet Name: </span>
<asp:TextBox ID="txtsheet" runat="server"> </asp:TextBox>
<asp:Label ID="lblmsg" runat="server"> </asp:Label>
</td>
</tr>
<tr>
<td> <asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" /> </td>
</tr>
</table>


Thanks & Regards
Santosh

Open Popup Wnidow With QueryString asp.net C#

How to open pop window using asp.net c#.
Here code descibes how to open popup window with passing a query string in popup page.

string popup = "<script language='javascript'>" + "window.open('poppage.aspx?data=" + HttpUtility.UrlEncode(qs.ToString()) + "','CustomPopUp', " + "'fullscreen=no,height=330,width=350,top=250,left=250,scrollbars=yes, dependant = yes, alwaysRaised = yes, menubar=no,resizable=no')" + "</script>";
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "PopupScript", popup,false);

If you want only popup message code is given below.
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),"MyMessage","alert('Please enter!')", true);

Thanks & Regards
Santosh

Nested GridView in asp.net using C#

 Nested GridView in asp.net using C#  
 Gridview within another gridview  
 This exmaple show how we can nest gridview.GridView inside other gridview for disply related data from database.Gridview can be nested in other Gridview control to display the related data of any item retrieved from database using C# code.  
 Steps:  
 1. Drag & drop a gridview in to the page.  
 2. Add a new template column to this gridview.  
 3. Place another gridview inside this template column.  
 <asp:GridView ID="GridView2" runat="server" EnableTheming="False" PageSize="15" Width="700px"  
 OnPageIndexChanging="GridView2_PageIndexChanging" OnRowDataBound="GridView2_RowDataBound"  
 AutoGenerateColumns="False">  
 <Columns>  
 <asp:TemplateField HeaderText="Employee Details">  
      <ItemTemplate>  
           <table>  
                <tr>  
                     <td>Company Name </td>  
                     <td>:</td>  
                     <td colspan="4"><asp:Label ID="lblCompany" runat="server" Text='<%# Bind("Company") %>'></asp:Label></td>                 
                </tr>  
                <tr>  
                     <td>Date</td>  
                     <td>:</td>  
                     <td colspan="4"><asp:Label ID="lblDate" runat="server">  
                </tr>  
           <tr>  
           <td colspan="6">  
                <asp:GridView ID="GridView1" runat="server" AllowPaging="True" EnableTheming="False"  
                PageSize="10" Width="100%" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False">  
                <Columns>   
                     <asp:BoundField DataField="User Name" HeaderText="Name">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="LoanName" HeaderText="Loan">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="Show Name" HeaderText="Payroll Month">  
                     <ItemStyle HorizontalAlign="Left" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="PDate" HeaderText="Paid Date">  
                     <ItemStyle HorizontalAlign="Center" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="OpeningBalance" HeaderText="Open Date">  
                     <ItemStyle HorizontalAlign="Right" />  
                     </asp:BoundField>  
                     <asp:BoundField DataField="PaidAmount" HeaderText="Amt. Paid">  
                     <ItemStyle HorizontalAlign="Right" >  
                     </asp:BoundField>   
                </Columns>  
                <RowStyle CssClass="reporttext" />  
                <EmptyDataTemplate>  
                <strong><span style="font-size: 10pt;">No Records....!</span> </strong>  
                </EmptyDataTemplate>  
                <PagerStyle CssClass="reportheader" />  
                <HeaderStyle CssClass="reportheader" Width="80px" />  
                <AlternatingRowStyle CssClass="reporttext" />  
                </asp:GridView>  
           </td>  
           </tr>   
           </table>  
      </ItemTemplate>  
 </asp:TemplateField>  
 </Columns>   
 </asp:GridView>  
 .cs code  
 protected void FirstGridBind()  
 {  
      DataTable dt1DataTable = new DataTable();  
      dt1.Columns.Add("CompanyName");  
      DataRow drDataRow = dt1DataTable.NewRow();  
      if (ddlCompany.SelectedValue != "0")  
      {  
           drDataRow["CompanyName"] = ddlCompany.SelectedItem.Text;  
      }  
      else  
      {  
           drDataRow["CompanyName"] = "All Companies";  
      }  
      dt1DataTable.Rows.Add(drDataRow);  
      GridView2.DataSource = dt1DataTable;  
      GridView2.DataBind();  
 }  
 protected void SecondGridBind()  
 {  
      foreach (GridViewRow row in GridView2.Rows)  
      {  
           Label lblDate = row.FindControl("lblDate") as Label;  
           if (txtFromDate.Text.Trim() != "" && txtToDate.Text.Trim() != "")  
           {  
                lblDate.Text = txtFromDate.Text.Trim() + " - " + txtToDate.Text.Trim();  
           }  
           else  
           {  
                lblDate.Text = "All Dates";  
           }  
           GridView GridView1 = row.FindControl("GridView1") as GridView;  
           string str = @"SELECT You query;  
           if (ddlCompany.SelectedValue != "0")  
           {  
           str += " AND (hrdEmployeeMaster.CompanyId = " + Convert.ToInt32(ddlCompany.SelectedValue) + ")";  
           }   
           DataTable dt = SqlHelper.ExecuteDataset(connString, CommandType.Text, str).Tables[0];  
           Session["myDataTable"] = dt;  
           GridView1.DataSource = dt;  
           GridView1.DataBind();  
           if (GridView1.Rows.Count > 0)  
           {  
           lbExport.Visible = true;   
           }  
      }  
 }  
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
 {  
      if (e.Row.RowType == DataControlRowType.DataRow)  
      {  
           if (GridView2.Rows.Count > 0)  
           {  
                GridView GridView1 = GridView2.Rows[0].FindControl("GridView1") as GridView;  
                e.Row.Cells[0].Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + SrNo);  
                SrNo++;  
           }  
      }  
 }  

JavaScript for textbox should be numeric

JavaScript for textbox should be numeric

This example show validate a textbox value is numeric.When you enter a non nemeric value
in textbox popup message will display.
<asp:TextBox ID="txtMinExperience" onKeyUp="benumeric();" runat="server" MaxLength="50" TabIndex="4"
Width="50px">0</asp:TextBox>

<script language="javascript" type="text/javascript">
function benumeric()
{
var txtMin=document.getElementById('<%=txtMinExperience.ClientID%>');
if(isNaN(txtMin.value)== true)
{
alert("This Field Should Be Numeric.");
txtMin.focus();
txtMin.value="";
return false;
}
return true;
}
</script>

Thanks & Regards
Santosh

JavaScript validation for dropdownlist

 JavaScript validation for dropdownlist  
 This example show how dropdownlist should be selected using javascript.  
   
 function validate()  
 {   
 var ddlCountry = document.getElementById('<%=ddlParameter.ClientID%>');   
 if(ddlCountry.value==0)  
 {  
 alert("Not Selected..!");  
 ddlParameter.focus();  
 return false;  
 }   
 return true;   
 }  
 Thanks & Regards  
 Santosh Singh  

JavaScript form Validation in asp.net

 JavaScript form Validation in asp.net  
 This simple code show how to do simple client side validation using javascript  
   
 Create a form with following:  
   
 1. Emp Name : <asp:TextBox ID="txtEmpName" />  
 2. Email : <asp:TextBox ID="txtEmailAdd" />  
 3. URL : <asp:TextBox ID="txturl" />  
 4. Zip : <asp:TextBox ID="txtZip" />  
   
 <asp:Button ID="btnAdd" OnClientClick=" return form_validate()" runat="server" Text="Submit" />  
   
 Write this javascript to your aspx page  
   
 <script language="javascript" type="text/javascript">  
 function form_validate()  
 {  
      if (document.getElementById("<%=txtEmpName.ClientID%>").value=="")  
      {  
           alert("Please enter the name");  
           document.getElementById("<%=txtEmpName.ClientID%>").focus();  
           return false;  
      }  
      if(document.getElementById("<txtEmailAdd.ClientID %>").value=="")  
      {  
           alert("Email id can not be blank");  
           document.getElementById("<%=txtEmailAdd.ClientID %>").focus();  
           return false;  
      }  
      var mailPattern = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;  
      var mailid=document.getElementById("<%=txtEmailAdd.ClientID %>").value;  
      var matchArr = mailid.match(mailPattern);  
      if (matchArr == null)  
      {  
           alert("Your email is incorrect.");  
           document.getElementById("<%=txtEmailAdd.ClientID %>").focus();  
           return false;  
      }  
      if(document.getElementById("<%=txturl.ClientID %>").value=="")  
      {  
           alert("Please enter URL");  
           document.getElementById("<%=txturl.ClientID %>").value="http://"  
           document.getElementById("<%=txturl.ClientID %>").focus();  
           return false;  
      }  
      var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"  
      var tempURL=document.getElementById("<%=txturl.ClientID%>").value;  
      var matchURL=tempURL.match(Url);  
      if(matchURL==null)  
      {  
           alert("URL incorrect try again||");  
           document.getElementById("<%=txturl.ClientID %>").focus();  
           return false;  
      }  
      if (document.getElementById("<%=txtZIP.ClientID%>").value=="")  
      {  
           alert("Zip Code not correct");  
           document.getElementById("<%=txtZIP.ClientID%>").focus();  
           return false;  
      }  
      var digits="0123456789";  
      var temp;  
      for (var i=0;i {  
      temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);  
      if (digits.indexOf(temp)==-1)  
      {  
           alert("Please enter correct zip code");  
           document.getElementById("<%=txtZIP.ClientID%>").focus();  
           return false;  
      }  
 }  
 return true;  
 }  
 </script>  
   
 Thanks & Regards  
 Santosh