Monday, August 23, 2010

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

Friday, April 30, 2010

Display all related data in comma separated list sql server

Concetenate the two fields and display the records with comma separated string in one field.

SELECT p_scrid,
SUBSTRING(
(
SELECT (' ,' + screen_name)
FROM tbl_SCRMst t2
WHERE t1.p_scrid = t2.p_scrid
ORDER BY
p_scrid,
screen_name
FOR XML PATH( '')
),3,1000)
FROM tbl_SCRMst t1
GROUP BY p_scrid

Thanks & Regards
Santosh

Saturday, April 3, 2010

Check record exist or not using asp.net and c#

This code show how to check record exist in database.Method get custid as a parameter and pass to stored procedure that will check record exist or not.

public bool IsCustomerExist(string strCust)
{
//SqlConnection objSqlConnection = null;
SqlCommand objSqlCommand = null;
try
{
//objSqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["StrConnect"].ToString());
objSqlCommand = new SqlCommand("usp_CheckCustomerExists", con);
objSqlCommand.CommandType = CommandType.StoredProcedure;
objSqlCommand.Parameters.Add("CustomerID", SqlDbType.Int, 4).Value = Convert.ToInt32(strCust);
con.Open();
SqlDataReader objSqlDataReader = objSqlCommand.ExecuteReader();
if (objSqlDataReader.HasRows)
return true;
else
return false;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
}

Thanks & Regards
Santosh