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  

HyperLinkink in Gridview

Hyperlink column in Gridview
Here i am describing very simple code for how to use Hyperlink column in Gridview

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
Height="1px" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="GridView1_RowDataBound"
Width="700px">
<Columns>
<asp:BoundField DataField="Designation" HeaderText="Designation">
</asp:BoundField>
<asp:BoundField DataField="ContactNo" HeaderText="Contact No.">
<ItemStyle Width="100px" />
<HeaderStyle Width="100px" />
</asp:BoundField>
<asp:HyperLinkField DataNavigateUrlFields="CandidateAppId" DataNavigateUrlFormatString="~/Salary/frmsalary.aspx?Id={0}"
HeaderText="Attach" Text="View">
<ItemStyle HorizontalAlign="Center" Width="50px" />
<HeaderStyle Width="50px" />
</asp:HyperLinkField>
<asp:TemplateField HeaderText="View">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<HeaderStyle HorizontalAlign="Center" Width="50px" />
<ItemTemplate>
<asp:ImageButton ID="ImageView" runat="server" ImageUrl="~/Image/img.png"
OnClick="ImageView_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<HeaderStyle Width="50px" />
<ItemTemplate>
<asp:ImageButton ID="ImgDelete" runat="server" ImageUrl="~/Image/img.png"
OnClick="ImgDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Thank & Regards
Santosh

How To Use Ajax

Hi....
you can start with vs2008..
1.just download ajaxcontrolkit.dll
2.copy this dll in your bin folder.
3.add reference by right click on your website brouwse and add ajaxcontrolkit.dll
4.add a new tab in your tolbox right click on toolbox add new tab and load aajax controll from bin folder.
5.now can find all ajax control in your tolbox ready for use.

GridView ScrollBar

How to make scrollable gridview.

<div style="overflow-y: scroll; height: 200px">
<asp:GridView ID="GridView1" runat="server" Font-Size="12px" BackColor="#FFFFFF"
GridLines="Both" CellPadding="4" Width="560">
<HeaderStyle BackColor="#EDEDED" Height="26px" />
</asp:GridView>
</div>

Thanks & Regards
Santosh

Add new row using GridView footer column

Adding new record in database from Gridview footer row

Abstract:
Here we will discuss about to add new recored in database using Gridview footer column.
Just drag and drop a gridview in your page and follow the below code.This code in three tier application
so i am writing here only front end code.


<asp:GridView ID="gvStudentDetail" runat="server" DataKeyNames="StudentDetailId" AllowPaging="True" PageSize="12"
AutoGenerateColumns="False" OnPageIndexChanging="gvStudentDetail_PageIndexChanging"
OnRowDataBound="gvStudentDetail_RowDataBound" TabIndex="2" Width="697px" OnRowCancelingEdit="gvStudentDetail_RowCancelingEdit"
OnRowEditing="gvStudentDetail_RowEditing" OnRowUpdating="gvStudentDetail_RowUpdating"
ShowFooter="True" OnRowCommand="gvStudentDetail_RowCommand" OnRowDeleting="gvStudentDetail_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Sr. No">
<ItemTemplate>
<asp:Label ID="lblSrNo" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="StudentDetailId" Visible="False">
<ItemTemplate>
<asp:Label ID="lblStudentDetailId" runat="server" Text='<%# Bind("StudentDetailId") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFooterStudentDetailId" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="StudentDetail">
<ItemTemplate>
<asp:Label ID="lblStudentDetail" runat="server" Text='<%# Bind("StudentDetail") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStudentDetail" runat="server" Text='<%# Bind("StudentDetail") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewStudentDetail" runat="server" Visible="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="ImgYes" runat="server" ImageUrl="~/Image/image_edit.png" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
ImageUrl="~/Image/imageupdate.png" Text="Update" />
<asp:ImageButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
ImageUrl="~/Image/imagecancel.png" Text="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="ButtonAdd" runat="server" ImageUrl="~/Image/imagerow_add.png" CommandName="AddNew"
ToolTip="Add New Record" />
<asp:ImageButton ID="lbtnAdd" runat="server" CausesValidation="True" CommandName="Add"
ImageUrl="~/Image/imageadd.png" Visible="false" Text="Add" />
<asp:ImageButton ID="lbtnCancel" runat="server" CausesValidation="False" CommandName="Cancel"
ImageUrl="~/Image/imagecancel.png" Visible="false" Text="Cancel" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImgDelete" runat="server" ImageUrl="~/Image/image_delete.png"
CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

----------------------------------------------------------------------------------------
protected void GridViewStudentDetail()
{
try
{
Ds = objStudentDetailBLL.GetData();
if (Ds.Tables[0].Rows.Count > 0)
{
gvStudentDetail.DataSource = Ds;
gvStudentDetail.DataBind();
}
else
{
ShowNoResultFound(Ds.Tables[0], gvStudentDetail);
}
}
catch (Exception ex)
{
exceptionMessage.Text = ex.Message;
}
}
protected void gvStudentDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");
lblSrNo.Text = SrNo.ToString();
SrNo++;
}
}
protected void gvStudentDetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvStudentDetail.PageIndex = e.NewPageIndex;
GridViewStudentDetail();
}
protected void gvStudentDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
StudentDetail.EditIndex = e.NewEditIndex;
GridViewStudentDetail();
}
protected void gvStudentDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

objStudentDetail.StudentDetailId = Convert.ToInt32(((Label)gvStudentDetail.Rows[e.RowIndex].FindControl("lblStudentDetailId")).Text);
objStudentDetail.StudentDetail = Convert.ToString(((TextBox)gvStudentDetail.Rows[e.RowIndex].FindControl("txtStudentDetail")).Text);
try
{
int intResultUpdate = objStudentDetailBLL.Update(objStudentDetailDetail);
if (intResultUpdate > 0)
{
exception.Text = "Record Updated Successfully !";
gvStudentDetail.EditIndex = -1;
GridViewStudentDetail();
}
}
catch (Exception ee)
{
exception.Text = ee.Message.ToString();
}
finally
{
objStudentDetailBLL = null;
}

}
protected void gvStudentDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvStudentDetail.EditIndex = -1;
GridViewStudentDetail();
}
protected void gvStudentDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
objStudentDetail.StudentDetailId = (int)gvStudentDetail.DataKeys[e.RowIndex].Value;
int result = objStudentDetailBLL.Delete(objStudentDetailDetail);
if (result > 0)
{
exception.Text = "Record Deleted Successfully !";
gvStudentDetail.EditIndex = -1;
GridViewStudentDetail();
}
}
catch(Exception ex)
{
exceptionText = ex.Message.ToString();

}
}
protected void gvStudentDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
ImageButton lbtnAdd = (ImageButton)gvStudentDetail.FooterRow.FindControl("lbtnAdd");
ImageButton lbtnCancel = (ImageButton)gvStudentDetail.FooterRow.FindControl("lbtnCancel");
ImageButton ButtonAdd = (ImageButton)gvStudentDetail.FooterRow.FindControl("ButtonAdd");
ButtonAdd.Visible = false;

TextBox txtNewStudentDetail= (TextBox)gvStudentDetail.FooterRow.FindControl("txtNewStudentDetail");
txtNewStudentDetail.Visible = true;
lbtnCancel.Visible = true;
lbtnAdd.Visible = true;

objStudentDetailDetail.StudentDetail = Convert.ToString(((TextBox)gvStudentDetailFooterRow.FindControl("txtNewStudentDetail")).Text);

if (e.CommandName.Equals("Add"))
{
try
{
if (objStudentDetailDetail.StudentDetail == "")
{
exceptionText = "Please Enter the StudentDetail!!";
}
else
{
int intResultUpdate = objStudentDetailBLL.Insert(objStudentDetail);
if (intResultUpdate > 0)
{
exception.Text = "Record Added Successfully !";
StudentDetail.EditIndex = -1;
GridViewStudentDetail();
}
}
}
catch (Exception ee)
{
exceptionMessage.Text = ee.Message.ToString();
}
finally
{
objStudentDetailBLL = null;
}
}
}

Monday, August 23, 2010

AJAX Accordian Example

<ajaxToolkit:Accordion ID="acdContactInfo" runat="server" SelectedIndex="0" FadeTransitions="true"
TransitionDuration="300" HeaderCssClass="accordHeader" ContentCssClass="accordionContent"
HeaderSelectedCssClass="accordHeaderSelected">
<Panes>
<ajaxToolkit:AccordionPane ID="empfirstAdd" runat="server" Width="100%">
<Header>>
First Address </Header>
<Content>
<table>
<tr>
<td colspan="4" style="text-align: left; height: 22px;">
<strong><span style="color: #999999">Present Address Details</span></strong>
</td>
<td style="width: 137px; text-align: left; height: 22px;">
</td>
<td style="text-align: left; height: 22px; width: 10px;">
</td>
<td style="width: 10px; height: 22px; text-align: left">
</td>
<td style="width: 187px; text-align: left; height: 22px;">
</td>
</tr>
<tr>
<td style="width: 204px; text-align: right; vertical-align: middle;" valign="top">
<strong>Address</strong>
</td>
<td style="width: 3px" valign="top">
<span style="color: #ff3333">*</span>
</td>
<td style="width: 3px" valign="top">
:
</td>
<td rowspan="3" style="width: 133px; text-align: left" valign="top">
<asp:TextBox ID="txtFAddress" runat="server" Height="53px" MaxLength="200"
TextMode="MultiLine" Width="200px"></asp:TextBox>
</td>
<td style="width: 137px; text-align: right; vertical-align: middle; height: 19px;"
valign="to">
<strong>Country</strong>
</td>
<td style="width: 10px; text-align: center; vertical-align: middle;" valign="top">
<span style="color: #ff3333">*</span>
</td>
<td style="vertical-align: middle; width: 10px; text-align: center" valign="top">
:
</td>
<td style="width: 187px; text-align: left" valign="top">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" DataTextField="CountryName"
DataValueField="CountryId" Height="20px" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
Width="144px">
<asp:ListItem Text="<Select Country>" Value="0"></asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td style="width: 204px; text-align: left" valign="top">
</td>
<td style="width: 3px" valign="top">
</td>
<td style="width: 3px" valign="top">
  
</td>
<td style="width: 137px; text-align: right; vertical-align: middle; height: 19px;"
valign="top">
<strong>State</strong>
</td>
<td style="width: 10px; text-align: center; vertical-align: middle;" valign="top">
<span style="color: #ff3333">*</span>
</td>
<td style="vertical-align: middle; width: 10px; text-align: center" valign="top">
:
</td>
<td style="width: 187px; text-align: left" valign="top">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" DataTextField="StateName"
DataValueField="StateId" Height="20px" OnSelectedIndexChanged="ddlState_SelectedIndexChanged"
Width="144px">
<asp:ListItem Text="<Select State>" Value="0"></asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td style="width: 204px; text-align: left; height: 19px;" valign="top">
</td>
<td style="width: 3px; height: 19px;" valign="top">
</td>
<td style="width: 3px; height: 19px;" valign="top">
  
</td>
<td style="width: 137px; text-align: right; vertical-align: middle; height: 19px;"
valign="top">
<strong>City</strong>
</td>
<td style="width: 10px; text-align: center; vertical-align: middle; height: 19px;"
valign="top">
<span style="color: #ff3333">*</span>
</td>
<td style="vertical-align: middle; width: 10px; height: 19px; text-align: center"
valign="top">
:
</td>
<td style="width: 200px; text-align: left; height: 19px;" valign="top">
<asp:DropDownList ID="ddlCity" runat="server" DataTextField="CityName" DataValueField="CityId"
Height="20px" Width="150px">
</asp:DropDownList>
</td>
</tr>
</table>
</Content>
</ajaxToolkit:AccordionPane>
<ajaxToolkit:AccordionPane ID="AccPaneEmpSecAdd" runat="server" Width="100%">
<Header>
Second Add</Header>
<Content>
<table>
<tr>
<td align="left" style="width: 204px; height: 16px; vertical-align: middle; text-align: right;">
<strong>Name</strong>
</td>
<td style="height: 16px; width: 2px;">
<span style="color: #ff3333">*</span>
</td>
<td style="width: 3px; height: 16px">
:
</td>
<td style="color: #000000; height: 24px" align="left">
<asp:TextBox ID="txtContName" runat="server" MaxLength="50" Width="188px"></asp:TextBox>
</td>
<td style="height: 19px; text-align: right; vertical-align: middle;">
<strong>Relation</strong>
</td>
<td style="width: 10px; height: 16px; text-align: left">
<span style="color: #ff3333">*</span>
</td>
<td style="width: 10px; height: 16px; text-align: left">
:
</td>
<td align="left" style="color: #000000; height: 24px">
<asp:DropDownList ID="ddlRelation" runat="server" Width="144px" DataTextField="Relation"
DataValueField="RelationId" Height="20px">
</asp:DropDownList>
</td>
<td style="width: 24px">
</td>
</tr>
</table>
</Content>
</ajaxToolkit:AccordionPane>
</Panes>
</ajaxToolkit:Accordion>

Thanks & Regards
Santosh

Simple GridView Bind code

<asp:GridView ID="GridView1" runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowDataBound="GridView1_RowDataBound"
PageSize="10"
Width="733px"
TabIndex="2";>
<Columns;>
<asp:BoundField HeaderText="Sr. No";>
<ItemStyle HorizontalAlign="Center" /;>
</asp:BoundField;>
<asp:TemplateField HeaderText="CityId" Visible="False";>
<EditItemTemplate;>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CityId") %>'></asp:TextBox;>
</EditItemTemplate;>
<ItemTemplate;>
<asp:Label ID="lblCityId" runat="server" Text='<%# Bind("CityId") %;>';></asp:Label;>
</ItemTemplate;>
</asp:TemplateField;>
<asp:BoundField DataField="CountryName" HeaderText="Country" /;>
<asp:BoundField DataField="StateName" HeaderText="State" /;>
</Columns;>


CS code...
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + SrNo);
SrNo++;
}
}
public void GridViewBind()
{
SqlConnection conn = new SqlConnection(connectionString);
Ds = SqlHelper.ExecuteDataset(myconn, "usp_CityMaster");
GridView1.DataSource = Ds;
GridView1.DataBind();
}
protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
CityBind();
}

Thanks & Regards
Santosh Singh

GridView find control

protected void ddlQty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gr = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
DropDownList ddlQty = (DropDownList)gr.FindControl("ddlQty");
if (ddlQty != null)
{

Label lblPrice = (Label)gr.FindControl("lblPrice");
Label lblOriginalPrice = (Label)gr.FindControl("lblOriginalPrice");
int price = Convert.ToInt32(lblOriginalPrice.Text);
int NewPrice = price * Convert.ToInt16(ddlQty.SelectedValue);
lblPrice.Text = Convert.ToString(NewPrice);

}
GridViewRow gr = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
DropDownList ddlQty = (DropDownList)gr.FindControl("ddlQty");
if (ddlQty != null)
{

Label lblPrice = (Label)gr.FindControl("lblPrice");
Label lblOriginalPrice = (Label)gr.FindControl("lblOriginalPrice");
int price = Convert.ToInt32(lblOriginalPrice.Text);
int NewPrice = price * Convert.ToInt16(ddlQty.SelectedValue);
lblPrice.Text = Convert.ToString(NewPrice);
}
}
Thanks & Regards
Santosh Singh

Enable textbox in gridview on click checkbox

JavaScript

function callonclick(obj)
{

var sdt = obj.split("_");
var chkDeny=document.getElementById('ctl00_ContentPlaceHolder1_gv_'+sdt[3]+'_chkDeny');
var txtReason=document.getElementById('ctl00_ContentPlaceHolder1_gv_'+sdt[3]+'_txtReason');
if(chkDeny.checked)
{
txtReason.value="";
txtReason.disabled =false;
}
else
{
txtReason.value="Enter Reason";
txtReason.disabled =true;

}
}


On Aspx page

<asp:TemplateField HeaderText="Deny">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkDeny" runat="server" onclick="callonclick(this.id);" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="30px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason">
<EditItemTemplate>
<asp:TextBox ID="txtsan" runat="server" TextMode="MultiLine" Width="80px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<table>
<tr>
<td valign="top">
</td>
<td>
<asp:TextBox ID="txtReason" runat="server" Height="40px" TextMode="MultiLine" Width="250px" Enabled="false">Enter Reason</asp:TextBox></td>
</tr>
</table>
<span style="font-size: 7pt"></span>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
==========================
Nother way Using cs code..

javascript

function StatusGridTextBox(txtReason)
{
document.getElementById(txtReason).disabled = !document.getElementById(txtReason).disabled;
}

on cs code

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{


if ((e.Row.RowType == DataControlRowType.DataRow))
{
((CheckBox)e.Row.FindControl("chkDeny")).Attributes.Add("onclick", "javascript:StatusGridTextBox('" + ((TextBox)e.Row.FindControl("txtReason")).ClientID + "')");
}

}

Thanks & Regards
Santosh

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

DataReader

A DataReader is a read-only forward-only way of reading data. It is quiet fast when compared to fetching data using a DataSet.
Some important point:
Read-only access
Supports a single table based on a single SQL query of one database
Connected mode
Bind to a single control
Forward-only scanning of data
Faster access to data
Lightweight object with very little overhead
Must be manually coded

Code Sample:
SqlConnection myconn = new SqlConnection(connString);
SqlCommand mycomm = new SqlCommand("select * from emp", myconn);
mycomm.Connection.Open();
SqlDataReader dr =
mycomm.ExecuteReader(CommandBehavior.CloseConnection);
while(dr.Read())
{
Console.WriteLined(r.GetString(0));
}
dr.Close();
myconn.Close();

Thanks & Regards
Santosh

CSS For FieldSet control in asp.net

.fldset
{
border: solid 1px #A8A8A8;
background-color:#FCFCFC;
display:inline;
}
.fldsetlegend
{
font-size:11px;
background-color: #56458C;
color:#FCFCFC;
font-weight:bold;
font-variant:small-caps;
padding: 0px 8px 2px 8px;
margin: 2px 0px 10px 0px;
}

Thanks & Regards
Santosh

CSS For AJAX Tab

.AJAXTab_Theme .tab_header
{
font-family:"Helvetica Neue", Arial, Sans-Serif;
background:url(/PNG/Light-menu.png) repeat-x bottom;
height:20PX ;
font-size:12px;
display:block;
}
.AJAXTab_Theme .tab_header .tab_outer
{
background:url(/Images/Tab/tab.png) no-repeat left top;
border-color:#222;
color:#222;
padding-left:10px;
margin-right:3px;
}
.AJAXTab_Theme .tab_header .ajax__tab_inner
{
background:url(PNG/Dark-menu.png) no-repeat right top;
border-color:#666;
color:#0067CA;
font:bold 10pt verdana;
padding:3px 10px 2px 0px;
}
.AJAXTab_Theme .ajax__tab_hover .ajax__tab_inner
{
color:#B80200;
font:bold 10pt verdana;
}
.AJAXTab_Theme .ajax__tab_active .tab_outer
{
background:url(PNG/Dark-menu.png) no-repeat 0pt -40px;
border-bottom-color:#ffffff;
}
.AJAXTab_Theme .tab_active .tab_inner
{
background:url(PNG/Dark-menu.png) no-repeat right -40px;
color:#B80200;
font:bold 10pt verdana;
border-color:#333
}
.AJAXTab_Theme .tab_body
{
font-family:verdana,tahoma,helvetica;
font-size:10pt;
padding:8px;
background-color:#ffffff;
border:solid 1px #d7d7d7;
border-top-width:0;
}

Thank & Regards
Santosh

Create pdf from datatable

How to create pdf from datatable in asp.net c#.
Solution is given below.

public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);

string clientLogo = System.Web.HttpContext.Current.Session["CompanyName"].ToString();
clientLogo = clientLogo.Replace(" ", "");
string clogo = clientLogo + ".jpg";

string imageFilePath = System.Web.HttpContext.Current.Server.MapPath("../ClientLogo/" + clogo + "");
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);

Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;

for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);

Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

Thanks & Regards
Santosh

Create autogenerate serial number in Gridview

Auto Generate Serial Number In Gridview

The Given code auto generate serial number with page index changing.
Generate Dynamic Serial Number in GridView is coommon task for many programmer

Here i explain it in very simple way
1: Drag GridView in you asp.net web page.
2: Go to Gridview properties and Click on Columns than add Template Column.
3:Code is given below

<asp:GridView ID="gv" runat="server" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Sr. No">
<ItemTemplate>
<asp:Label ID="lblSrNo" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="50px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="EmpName">
<ItemTemplate>
<asp:Label ID="lblEmpName" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="50px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblSrNo = (Label)e.Row.FindControl("lblSrNo");
lblSrNo.Text = SrNo.ToString();
SrNo++;
int pageNum = gv.PageIndex * gv.PageSize + Sr;
e.Row.Cells[1].Text = pageNum.ToString();
}
}

Thanks & Regards
Santosh

How to check Record Exist in table before insert

Here i am explain you check if record is not exist in database then insert otherwise update the table.

CREATE PROCEDURE [dbo].[uspInst_Addupdate]
(
@InstId int,
@Inst varchar(50),
)
AS
BEGIN
IF @InstId=0
BEGIN
IF NOT EXISTS(SELECT * FROM InstMaster WHERE Inst= @Inst)
INSERT INTO InstMaster(Inst) VALUES(@Inst)
END
ELSE
BEGIN
UPDATE InstMaster
SET Inst= @Inst WHERE (Inst= @Inst)
END
END

Thanks & Regards
Santosh

Change GridView RowColor

How to change gridview row color and use css class.
Below code describe how to call css class at runtime for change the gridview row color.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string checkstatus= Convert.ToString(DataBinder.Eval(e.Row.DataItem,"checkstatus"));
if (checkstatus == "Pending")
{
e.Row.Cells[0].BackColor="css class";
}
else
{
e.Row.Cells[0].BackColor="css class";
}
}
}

Thanks & Regards
Santosh

How to change DateFormat

string[] str = txtIssuedOnVisa.Text.Trim().Split('/');
string strIssuedOn = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();

Thanks & Regards
Santosh

Cascading Dropdownlist

ASPX Page

<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack="True" DataTextField="CountryName"
DataValueField="CountryId" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged";>
<asp:ListItem Value="0" Text="<Select Country;>";></asp:ListItem;>
</asp:DropDownList;>
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" DataTextField="StateName"
DataValueField="StateId" OnSelectedIndexChanged="ddlState_SelectedIndexChanged";>
</asp:DropDownList;>
<asp:DropDownList ID="ddlCity" runat="server" DataTextField="CityName" DataValueField="CityId";>
</asp:DropDownList;>

CS Page

if (!Page.IsPostBack)
{
CountryBind();
}
protected void CountryBind()
{
string sqlQuery = "Select * from Country;

using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlCountry.DataSource = ds;
ddlCountry.DataBind();
conn.Close();
}
}
protected void StateBind()
{
string sqlQuery = "SELECT * FROM State " + " WHERE (CountryId = " + Convert.ToInt32(ddlCountry.SelectedValue) + " )";
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlState.DataSource = ds;
ddlState.DataBind();
conn.Close();
}
}
protected void CityBind()
{
string sqlQuery = "SELECT * FROM City " + " WHERE (StateId = " + Convert.ToInt32(ddlState.SelectedValue) + " )";
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
ddlCity.DataSource = ds;
ddlCity.DataBind();
conn.Close();
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
StateBind();
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
CityBind();
}

Thanks & Regards
Santosh Singh

Authentication And Authorization

Authentication And Authorization
Authentication is the process of identification and validation of a user's credentials. After the identity is authenticated,
a process called authorization determines whether that identity has access to a particular resource.
ASP.NET provides three ways to authenticate a user:
Forms authentication
Windows authentication
Passport authentication

Setting in web.config file given below

Forms authentication
<configuration>
<system.web>
<authentication mode="Forms"/>
<forms name="login"loginUrl="loginPage.aspx" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>

Windows authentication
<authentication mode="Windows"/>
<authorization>
<allow users ="*" />
</authorization>

Passport authentication
<configuration>
<system.web>
<authenticationmode="Passport">
<passportredirectUrl="loginPage.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>

Thanks & Regards
Santosh Singh

Saturday, August 14, 2010

Javascript date validation

function DateValid()
{
var sDate = document.getElementById('').value;
var eDate = document.getElementById('').value;
var endDate = new Date(eDate );
var startDate= new Date(sDate );
if(sDate != '' && eDate != '' && startDate > endDate )
{
alert("Start date should be greater than End Date.");
return false;
}
if(sDate == eDate )
{
alert("Start date should be greater than End Date.");
return false;
}
}

Thanks & Regards
Santosh Singh

Monday, August 9, 2010

When Gridview has no record display empty grid at runtime

When GridView(Add New Record) has no record display empty Grid at runtime.
Some time when we adding new row in gridview footer column and there is no record in database,so what we can do?
So we can disply message no record found and add new button show for adding new record.
Here is solution display runtime empty gridview.
 private void ShowNoResultFound(DataSet ds,GridView gv)
{
DataTable dt = (DataTable)ds.Tables[0];
dt.Rows.Add(dt.NewRow());
gv.DataSource = dt;
gv.DataBind();
int TotalColumns = gv.Rows[0].Cells.Count;
gv.Rows[0].Cells.Clear();
gv.Rows[0].Cells.Add(new TableCell());
gv.Rows[0].Height = 0;
gv.Rows[0].Visible = false;
}
Thanks & Regards
Santosh Singh


Wednesday, August 4, 2010

Session object in asp.net

Session object:

Session object is used to store state specific information per client basis. It is specific to particular user.
Session data persists for the duration of user session you can store session's data on web server in different ways.
Session state can be configured using the section in the application's web.config file.

Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability

1.In process mode (in-memory)- State information is stored in memory of web server
2.Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
3.Database mode – session state is maintained on a SQL Server database.

In process mode:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server

Configuration information:



Advantages:
Fastest mode
Simple configuration

Disadvantages:
Session data will be lost if the worker process or application domain recycles
Not ideal for web gardens and web farms

Out-of-process Session mode (state server mode):

This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service
which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.

Net start aspnet_state

Configuration information:



Advantages:
Supports web farm and web garden configuration
Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
Out-of-process mode provides slower access compared to In process
Requires serializing data

SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that
persists across IIS restarts.
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.

Configuration Information:


Advantages:
Supports web farm and web garden configuration
Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.

Disadvantages:
Requires serialization of objects



Mode:
This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.

Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value;
Default session timeout value is 20 minutes

SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.

Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies
a process running over a network.

You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file
to reduce overhead for the entire application.

Thanks & Regards
Santosh Singh

Tuesday, August 3, 2010

AJAX

AJAX tab control
Here i describing a simple example how to use tab control in asp.net

.aspx code

< ajaxToolkit:TabPanel ID="tabFirst" runat="server" Width="111px" >
< HeaderTemplate>
First Tab Header name
< /HeaderTemplate>
< ContentTemplate>
< br />
< asp:GridView ID="gvEmpDetail" runat="server" DataKeyNames="EmpId" AllowPaging="True" PageSize="12"
AutoGenerateColumns="False" OnPageIndexChanging="gvEmpDetail_PageIndexChanging"
OnRowDataBound="gvEmpDetail_RowDataBound" TabIndex="2" Width="697px" OnRowCancelingEdit="gvEmpDetail_RowCancelingEdit"
OnRowEditing="gvEmpDetail_RowEditing" OnRowUpdating="gvEmpDetail_RowUpdating"
ShowFooter="True" OnRowCommand="gvEmpDetail_RowCommand" OnRowDeleting="gvEmpDetail_RowDeleting">
< Columns>
< asp:TemplateField HeaderText="Sr. No">
< ItemTemplate>
< asp:Label ID="lblSrNo" runat="server"> </asp:Label>
< /ItemTemplate>
< ItemStyle HorizontalAlign="Center" Width="50px" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="EmpId" Visible="False">
< ItemTemplate>
< asp:Label ID="lblEmpId" runat="server" Text=' <%# Bind("EmpId") %>'> </asp:Label>
< /ItemTemplate>
< FooterTemplate>
< asp:Label ID="lblFooterEmpId" runat="server"> </asp:Label>
< /FooterTemplate>
< /asp:TemplateField>
< asp:TemplateField HeaderText="Emp">
< ItemTemplate>
< asp:Label ID="lblEmp" runat="server" Text=' <%# Bind("Emp") %>'> </asp:Label>
< /ItemTemplate>
< EditItemTemplate>
< asp:TextBox ID="txtEmp" runat="server" Text=' <%# Bind("Emp") %> '> </asp:TextBox>
< /EditItemTemplate>
< FooterTemplate>
< asp:TextBox ID="txtNewEmp" runat="server" Visible="false"> </asp:TextBox>
< /FooterTemplate>
< FooterStyle HorizontalAlign="Left" />
< ItemStyle HorizontalAlign="Left" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="Edit">
< ItemTemplate>
< asp:ImageButton ID="ImgYes" runat="server" ImageUrl="~/Image/img_edit.png" CommandName="Edit" />
< /ItemTemplate>
< EditItemTemplate>
< asp:ImageButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
ImageUrl="~/Image/update.png" Text="Update" />
< asp:ImageButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
ImageUrl="~/Image/cancel.png" Text="Cancel" />
< /EditItemTemplate>
< FooterTemplate>
< asp:ImageButton ID="ButtonAdd" runat="server" ImageUrl="~/Image/row_add.png" CommandName="AddNew"
ToolTip="Add New" />
< asp:ImageButton ID="lbtnAdd" runat="server" CausesValidation="True" CommandName="Add"
ImageUrl="~/Image/add.png" Visible="false" Text="Add" />
< asp:ImageButton ID="lbtnCancel" runat="server" CausesValidation="False" CommandName="Cancel"
ImageUrl="~/Image/cancel.png" Visible="false" Text="Cancel" />
< /FooterTemplate>
< FooterStyle HorizontalAlign="Center" Width="120px" />
< ItemStyle HorizontalAlign="Center" Width="120px" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="Delete">
< ItemTemplate>
< asp:ImageButton ID="ImgDelete" runat="server" ImageUrl="~/Image/img_delete.png"
CommandName="Delete" OnClientClick="return ConfirmDelete();" />
< /ItemTemplate>
< ItemStyle HorizontalAlign="Center" Width="80px" />
< /asp:TemplateField>
< /Columns>
< /asp:GridView>
< asp:Label ID="exceptionMessage" runat="server" ForeColor="Red" Width="498px"> </asp:Label>
< /ContentTemplate>
< /ajaxToolkit:TabPanel>

< ajaxToolkit:TabPanel ID="tabEmpInfo" runat="server" >
< HeaderTemplate>
Emp Information
< /HeaderTemplate>
< ContentTemplate>
< br />
< asp:GridView ID="gvEmpInfo" runat="server" AllowPaging="True" AutoGenerateColumns="False" PageSize="12"
OnPageIndexChanging="gvEmpInfo_PageIndexChanging" OnRowDataBound="gvEmpInfo_RowDataBound"
TabIndex="2" Width="697px" OnRowCancelingEdit="gvEmpInfo_RowCancelingEdit" OnRowEditing="gvEmpInfo_RowEditing"
OnRowUpdating="gvEmpInfo_RowUpdating" ShowFooter="True" OnRowCommand="gvEmpInfo_RowCommand"
OnRowDeleting="gvEmpInfo_RowDeleting" DataKeyNames="EmpInfoId">
< Columns>
< asp:TemplateField HeaderText="Sr. No">
< ItemTemplate>
< asp:Label ID="lblSrNo" runat="server"> </asp:Label>
< /ItemTemplate>
< ItemStyle HorizontalAlign="Center" Width="50px" />
< /asp:TemplateField>
< /Columns>
< /asp:GridView>
< asp:Label ID="exceptionEmpInfo" runat="server" ForeColor="Red" Width="498px"> 0)
{
gvEmpDetail.DataSource = Ds;
gvEmpDetail.DataBind();
}
else
{
ShowNoResultFound(Ds.Tables[0], gvEmpDetail);
}
}
catch (Exception ex)
{
exceptionMessage.Text = ex.Message;
}
}
protected void GridViewEmpInfo()
{
try
{
Ds = objEmpInfoBLL.GetEmpInfoData();
if (Ds.Tables[0].Rows.Count > 0)
{
gvEmpInfo.DataSource = Ds;
gvEmpInfo.DataBind();
}
else
{
ShowNoResultFound(Ds.Tables[0], gvEmpInfo);
}
}
catch (Exception ex)
{
exceptionEmpInfo.Text = ex.Message;
}
}

Thanks & Regards
Santosh Singh

Monday, August 2, 2010

Gridview custom sorting using asp.net c#

public partial class _Default : System.Web.UI.Page
{
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SortGridView(sortExpression, "");
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;

return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void gvCust_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;

if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
static string sortExpression;
private void SortGridView(string sortExpression, string direction)
{
SqlConnection con;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnect"].ToString());
con.Open();
SqlDataAdapter oAdapter = new SqlDataAdapter("usp_GetCustDetail", con);
oAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet oDataSet = new DataSet();
oAdapter.Fill(oDataSet);
DataTable dt = oDataSet.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
gvCust.DataSource = dv;
gvCust.DataBind();
}
}

Thanks & Regards
Santosh