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