52

Send Email With Attachment In Asp.Net

This example shows how to Send Email With Attachment In Asp.Net 2.0,3.5,4.0 C# And VB.NET Using FileUpload Control. I am saving the uploaded file into memory stream rather then saving it on server.

Send Email With Attachment in Asp.Net
For this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server.

For sending E-mail, first of all we need to add Syatem.Net.Mail namespace in code behind of aspx page. 

In my previous article i describe how to send mail using gmail in asp.net 

Create the page as shown in the image above, put textbox for message and FileUpload Control for adding the file attachment.

Write following code in click event of Send button in Code behind of page

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

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

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        //mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = new MailAddress(txtFrom.Text);
        mail.Subject = txtSubject.Text;
        mail.Body = txtMessage.Text;
        mail.IsBodyHtml = true;

        //Attach file using FileUpload Control and put the file in memory stream
        if (FileUpload1.HasFile)
        {
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("YourGmailID@gmail.com", "YourGmailPassword");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }
}


VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim mail As New MailMessage()
        mail.[To].Add(txtTo.Text)
        'mail.To.Add("amit_jain_online@yahoo.com");
        mail.From = New MailAddress(txtFrom.Text)
        mail.Subject = txtSubject.Text
        mail.Body = txtMessage.Text
        mail.IsBodyHtml = True
        
        'Attach file using FileUpload Control and put the file in memory stream
        If FileUpload1.HasFile Then
            mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
        End If
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
            
        smtp.Send(mail)
    End Sub
End Class

Build and run the application to test the code

26

ASP.NET Open PopUp Window Update Refresh Values

This example explains how to Open PopUp Window In Asp.Net And Update Refresh Parent Child Values using ClientScript And RegisterStartupScript.
I am opening popup window from aspx page and updating values in parent window from child or popup window using javascript and ClientScript.RegisterStartupScript.

Open PopUp Window In Asp.Net
I have added to labels in Default.aspx page and one button to open popup window.

I've also added a PopUp.aspx page which is having two textboxes and a button to update lable values of parent page.

The textboxes in popup window are populated with Text values of lables in parent page (Default.aspx), after making changes in textbox values i'm updating values back in parent page.

HTML source Parent page
<form id="form1" runat="server">
<div>
First Name :
<asp:Label ID="lblFirstName" runat="server" Text="amiT">
</asp:Label><br />
 <br />
Last Name:&nbsp;
<asp:Label ID="lblLastName" runat="server" Text="jaiN">
</asp:Label><br />
<br />
<asp:Button ID="btnPop" runat="server" Text="Click To Edit Values" />
</div>
</form>


Write following JavaScript in Head section of page.
   1:  <script type="text/javascript">
   2:  function openPopUp()
   3:  {
   4:   var popUrl = 'PopUp.aspx?fn=' + document.getElementById('<%= lblFirstName.ClientID %>').innerHTML + '&ln=' + document.getElementById('<%= lblLastName.ClientID %>').innerHTML;
   5:   var name = 'popUp';
   6:   var appearence ='dependent=yes,menubar=no,resizable=no,'+
   7:                   'status=no,toolbar=no,titlebar=no,' +
   8:                   'left=5,top=280,width=230px,height=140px';
   9:  var openWindow = window.open(popUrl, name, appearence);
  10:  openWindow.focus();
  11:  }
  12:  </script>


In this i m getting values of lables and passing them to popuup page as querystrings

Write this code in Page_Load event of Default.aspx (parent) page
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
 string updateValuesScript = 
@"function updateValues(popupValues)
{
 document.getElementById('lblFirstName').innerHTML=popupValues[0];
 document.getElementById('lblLastName').innerHTML=popupValues[1];
}";
        
this.ClientScript.RegisterStartupScript(Page.GetType(), 
"UpdateValues", updateValuesScript.ToString(), true);
btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateValuesScript As String = "function updateValues(popupValues)" & vbCr & vbLf & "{" & vbCr & vbLf & " document.getElementById('lblFirstName').innerHTML=popupValues[0];" & vbCr & vbLf & " document.getElementById('lblLastName').innerHTML=popupValues[1];" & vbCr & vbLf & "}"
    
    Me.ClientScript.RegisterStartupScript(Page.[GetType](), "UpdateValues", updateValuesScript.ToString(), True)
    btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')")
End Sub

HTML SOURCE OF PopUp.aspx(child) page

<form id="form1" runat="server">
<div>
First Name :
<asp:TextBox ID="txtPopFName" runat="server" Width="113px">
</asp:TextBox><br />
<br />
Last Name:<asp:TextBox ID="txtPopLName" runat="server" 
                       Width="109px">
</asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
            Text="Button" /></div>
</form>


C# CODE PopUp.aspx
protected void Page_Load(object sender, EventArgs e)
{
 string updateParentScript = 
 @"function updateParentWindow()
 {                                                                               
   var fName=document.getElementById('txtPopFName').value;     
   var lName=document.getElementById('txtPopLName').value;   
   var arrayValues= new Array(fName,lName);
   window.opener.updateValues(arrayValues);       
   window.close(); 
 }";
 this.ClientScript.RegisterStartupScript(this.GetType(), 
     "UpdateParentWindow", updateParentScript, true);
 if (!IsPostBack)
 {
   txtPopFName.Text = Request["fn"];
   txtPopLName.Text = Request["ln"];
 }
   Button1.Attributes.Add("onclick", "updateParentWindow()");
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim updateParentScript As String = "function updateParentWindow()" & vbCr & vbLf & " {                                                                               " & vbCr & vbLf & "   var fName=document.getElementById('txtPopFName').value;     " & vbCr & vbLf & "   var lName=document.getElementById('txtPopLName').value;   " & vbCr & vbLf & "   var arrayValues= new Array(fName,lName);" & vbCr & vbLf & "   window.opener.updateValues(arrayValues);       " & vbCr & vbLf & "   window.close(); " & vbCr & vbLf & " }"
    Me.ClientScript.RegisterStartupScript(Me.[GetType](), "UpdateParentWindow", updateParentScript, True)
    If Not IsPostBack Then
        txtPopFName.Text = Request("fn")
        txtPopLName.Text = Request("ln")
    End If
    Button1.Attributes.Add("onclick", "updateParentWindow()")
End Sub

Hope this helps

Download sample code attached



26

AutoCompleteExtender TextBox CompletionList Width Ajax ASP.NET

Set AutoCompleteExtender TextBox CompletionList Width And Style With CSS Ajax ASP.NET. In this example i am setting Width of Completion List in Ajax AutoComplete Extender TextBox.

The default behavior of completion list takes width equal to the width of textbox. we can change this behavior by applying some CSS style to set the width we want. default width is as shown below in the Image.

 AutoCompleteExtender TextBox CompletionList Width And Style With CSS
I have also explained how to implement AutoComplete Extender TextBox In EditItemTemplate Of GridView

I have also created example to Add Progress Image in Ajax AutoComplete TextBox




In AutoComplete Extender default width of completion list is equals to the width of textbox, to fix this issue write the CSS script mentioned below in Head section of html source of page
<head runat="server">
    <title>Progress Image in AutoComplete TextBox</title>
<style>
        .AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
            font-weight: normal;
            border: solid 1px #006699;
            line-height: 20px;
            padding: 10px;
            background-color: White;
            margin-left:10px;
        }
        .AutoExtenderList
        {
            border-bottom: dotted 1px #006699;
            cursor: pointer;
            color: Maroon;
        }
        .AutoExtenderHighlight
        {
            color: White;
            background-color: #006699;
            cursor: pointer;
        }
        #divwidth
        {
          width: 150px !important;    
        }
        #divwidth div
       {
        width: 150px !important;   
       }
 </style>
</head>
The code in bold is setting the width of completion list, you can change the dimensions according to your needs.

Now Put a div with id "divwidth" above the html source of autocomplete extender
<div ID="divwidth"></div>

and add this line in autocomplete extender HTML source

CompletionListElementID="divwidth"

The complete html source of AutoComplete Extender will look like
<asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</asp:TextBox>   
<div ID="divwidth"></div>
<ajaxToolkit:AutoCompleteExtender runat="server" 
             ID="AutoComplete1"
             BehaviorID="autoComplete"
             TargetControlID="txtAutoComplete"
             ServicePath="AutoComplete.asmx" 
             ServiceMethod="GetCompletionList"
             MinimumPrefixLength="1" 
             CompletionInterval="10"
             EnableCaching="true"
             CompletionSetCount="12"
             CompletionListCssClass="AutoExtender"
             CompletionListItemCssClass="AutoExtenderList"
             CompletionListHighlightedItemCssClass
             ="AutoExtenderHighlight"
             CompletionListElementID="divwidth">
<ajaxToolkit:AutoCompleteExtender>

And this is how the AutoComplete TextBox will look like
AutoComplete List Width CSS style


Hope this helps


24

Detect Page Refresh In ASP.NET

This post explains how to Detect Page Refresh In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. If you have created a aspx page and have put a button on it, And in Click event of this button if you are inserting some data in database, after click if user refresh the page than click event gets fired again resulting data insertion to database again.

To stop events on the page getting fired on browser refresh we need to write bit of code to avoid it

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello.

HTML SOURCE OF PAGE


<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label><br />
<br />
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Button" /></div>
</form>
</body>
</html>

In Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it
Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed
C# Code Bihind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}

}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() ==
ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}

protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}


Download the Sample Code



24

Pass Send GridView Row Value/Data Using Hyperlink In ASP.NET

In this example i am describing how to Pass Transfer Or Send GridView Row Data Values To Other asp.net page using hyperlink.

Pass Transfer Send GridView Row Data Values With Hyperlink
I've put a hyperlink column in gridview to pass values through querystring, and using request.querystring on the second page to retrieve values.

You would also like to read
LinkButton in GridView and QueryString in ASP.NET to pass data


We need to set DataNavigateUrlFields and DataNavigateUrlFormatString properties of hyperlink in gridview to pass the row data 
HTML markup of the page


<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ID,Name,Location" 
DataNavigateUrlFormatString=
"Default2.aspx?id={0}&name={1}&loc={2}" 
Text="Transfer values to other page" />
<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" 
                SortExpression="Name" />
<asp:BoundField DataField="Location" HeaderText="Location" 
                SortExpression="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Now write code mentioned below to retrieve values on Default2.aspx page
C# code behind
protected void Page_Load(object sender, EventArgs e)
    {
        string strID = Request.QueryString["id"];
        string strName = Request.QueryString["name"];
        string strLocation = Request.QueryString["loc"];
        lblID.Text = strID;
        lblName.Text = strName;
        lblLocation.Text = strLocation;
    }
VB.NET code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim strID As String = Request.QueryString("id")
    Dim strName As String = Request.QueryString("name")
    Dim strLocation As String = Request.QueryString("loc")
    lblID.Text = strID
    lblName.Text = strName
    lblLocation.Text = strLocation
End Sub

Hope this helps


8

NULL In GridView EVAL Calling ServerSide Method In ItemTemplate

This example explains how to handle NULL In GridView EVAL Calling Serverside Method In ItemTemplate

In this example i am going to describe how to handle NULL values from DataBase in Eval method of GridView ItemTemplate or How to call Server side method written in code behind in ItemTemplate of GridView.

Handle NULL In GridView

My Table in database look like as shown in image below, some columns contains NULL values and i'll be showing "No Records Found" instead of NULL values in GridView.

To achieve this i've written a Method in code behind and will be calling this method in ItemTemplate of GridView.




Html source of GridView
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false">
<Columns>
<asp:BoundField ShowHeader="true" DataField="ID" 
                              HeaderText="ID" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Name")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Location")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ID, Name, Location FROM Details">
</asp:SqlDataSource>

In above code i am calling server side method CheckNull written in code behind from ItemTemplate of GridView which check the NULL values and change it as we want.
C# code for the CheckNull method
protected string CheckNull(object objGrid)
    {
        if (object.ReferenceEquals(objGrid, DBNull.Value))
        {
            return "No Record Found";
        }
        else
        {
            return objGrid.ToString();
        }
     }
VB.NET code behind
Protected Function CheckNull(ByVal objGrid As Object) As String
    If Object.ReferenceEquals(objGrid, DBNull.Value) Then
        Return "No Record Found"
    Else
        Return objGrid.ToString()
    End If
End Function


And this is how gridview will render


Hope this helps


76

Send Email Using Gmail In ASP.NET

This example shows how to Send Email Using Gmail In ASP.NET. If you want to send mail using Gmail account or it's SMTP server in ASP.NET application if you don't have a working smtp server to send mails than sending e-mail with Gmail is best option.

you need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)
{
  MailMessage mail = new MailMessage();
  mail.To.Add("Email ID where email is to be send");
  mail.To.Add("Another Email ID where you wanna send same email");
  mail.From = new MailAddress("YourGmailID@gmail.com");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail
 
Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage() 
  mail.To.Add("Email ID where you wanna send email")
  mail.To.Add("Email ID where you wanna send copy of email")
  mail.From = New MailAddress("YourGmailID@gmail.com")
  mail.Subject = "Email using Gmail"
 
  String Body = "Hi, this mail is to test sending mail"+ 
                "using Gmail in ASP.NET"
  mail.Body = Body
 
  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient() 
  smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
       ("YourUserName@gmail.com","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub


You also need to enable POP by going to settings > Forwarding and POP in your gmail account

Change YourUserName@gmail.com to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file
<system.net>
<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587
smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

Hope this helps


20

RadioButtonList DropDownList In GridView Edit Mode In ASP.NET

In this example i'm explaining how to use DropDownList Or RadioButtonList In GridView Edit Mode EditItemTemaplate In ASP.NET Using C# VB.NET

RadioButton and DropDOwnList are selected in edit mode based on value saved in DataBase



HTML markup of aspx page is mentioned below
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" 
              AutoGenerateColumns="False" 
              DataSourceID="SqlDataSource1" 
              OnRowDataBound="GridView1_RowDataBound" 
              OnRowUpdated="GridView1_RowUpdated" 
              OnRowUpdating="GridView1_RowUpdating" 
              OnRowEditing="GridView1_RowEditing">
 <Columns>
 <asp:TemplateField HeaderText="ID">
 <ItemTemplate>
 <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'>
 </asp:Label>
 </ItemTemplate>
 </asp:TemplateField>
 
 <asp:BoundField DataField="Name" HeaderText="Name" 
                 SortExpression="Name" />
 <asp:TemplateField HeaderText="Gender">
 <ItemTemplate>
 <asp:Label ID="lblGender" runat="server" 
            Text='<%#Eval("Sex") %>'>
 </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:RadioButtonList ID="rbGenderEdit" runat="server">
 <asp:ListItem>Male</asp:ListItem>
 <asp:ListItem>Female</asp:ListItem>
 </asp:RadioButtonList>
 </EditItemTemplate>
 </asp:TemplateField>
 
 <asp:TemplateField HeaderText="Marital Status">
 <ItemTemplate>
 <asp:Label ID="lblStatus" runat="server" 
            Text='<%#Eval("MaritalStatus") %>'>
 </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:DropDownList ID="ddlStatusEdit" runat="server">
 <asp:ListItem>Single</asp:ListItem>
 <asp:ListItem>Married</asp:ListItem>
 </asp:DropDownList>
 </EditItemTemplate>
 </asp:TemplateField>
 <asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Sex], [MaritalStatus] 
               FROM [Details]" 
UpdateCommand="Update Details Set [Name]=@Name, [Sex]=@Sex, 
              [MaritalStatus]=@MaritalStauts Where [ID]=@ID">
   <UpdateParameters>
       <asp:Parameter Name="Name" />
       <asp:Parameter Name="Sex" />
       <asp:Parameter Name="ID" />
       <asp:Parameter Name="MaritalStauts" />
   </UpdateParameters>
</asp:SqlDataSource>

C# Code Behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 DataRowView dRowView = (DataRowView)e.Row.DataItem;
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
   if ((e.Row.RowState & DataControlRowState.Edit) > 0)
   {
     RadioButtonList rblGender = (RadioButtonList)e.Row.FindControl("rbGenderEdit");
     DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatusEdit");
     rblGender.SelectedValue = dRowView[2].ToString();
     ddlStatus.SelectedValue = dRowView[3].ToString();
   }
 }
       
}
   
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
 RadioButtonList rblGender = (RadioButtonList)GridView1.Rows[e.RowIndex].FindControl("rbGenderEdit");
 DropDownList ddlStatus = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlStatusEdit");
 SqlDataSource1.UpdateParameters["Sex"].DefaultValue = rblGender.SelectedValue;
 SqlDataSource1.UpdateParameters["MaritalStauts"].DefaultValue = ddlStatus.SelectedValue;
}
VB.NET Code Behind
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    Dim dRowView As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
    If e.Row.RowType = DataControlRowType.DataRow Then
        If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
            Dim rblGender As RadioButtonList = DirectCast(e.Row.FindControl("rbGenderEdit"), RadioButtonList)
            Dim ddlStatus As DropDownList = DirectCast(e.Row.FindControl("ddlStatusEdit"), DropDownList)
            rblGender.SelectedValue = dRowView(2).ToString()
            ddlStatus.SelectedValue = dRowView(3).ToString()
        End If
        
    End If
End Sub

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
    Dim rblGender As RadioButtonList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("rbGenderEdit"), RadioButtonList)
    Dim ddlStatus As DropDownList = DirectCast(GridView1.Rows(e.RowIndex).FindControl("ddlStatusEdit"), DropDownList)
    SqlDataSource1.UpdateParameters("Sex").DefaultValue = rblGender.SelectedValue
    SqlDataSource1.UpdateParameters("MaritalStauts").DefaultValue = ddlStatus.SelectedValue
End Sub

Hope this helps.

Download sample code attached



Other posts in C# and ASP.NET
1.OpenFileDialog in winforms windows forms C# .NET VB.NET windows application
2.Find IP Address in ASP.NET Behind Proxy
3.Export GridView to Pdf using iTextSharp ASP.NET
4.Hide GridView Columns In ASP.NET C# VB.NET
5.Change Mode of DetailsView or FormView when Default Mode is Set to Insert in ASP.NET
6.Creating winforms AutoComplete TextBox using C# in Windows application
7.Disable copy paste cut and right click in textbox on aspx page using javascript

29

Cross Page Posting PostBack In ASP.NET

In this example i am showing how to use Cross Page Posting or Postback In ASP.NET 2.0, 3.5, 4.0 Using C# And VB.NET. Cross Page posting is used to submit a form on one page (say default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx)

There are two ways we can use cross page postsbacks in ASP.NET

1st method
In this i've created a Default.aspx page with two textbox and one button , button click will post back to Default2.aspx and there we will retrieve and show values of both textboxes

Html source of Default.aspx page is like

<%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox><br /><br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br /><br /><br />
        
<asp:Button ID="btnSubmit" runat="server" 
            OnClick="btnSubmit_Click" 
            PostBackUrl="~/Default2.aspx"
            Text="Submit to Second Page" /><br />
</div>
</form>
</body>
</html>
Don't forget to set PostBackUrl Property of Button
PostBackUrl="~/Default2.aspx"

Now to retrieve values of textBoxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx)
C# code behind
protected void Page_Load(object sender, EventArgs e)
{
    //Check whether previous page is cross page post back or not
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        TextBox txtPbFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
        TextBox txtPbLastName = (TextBox)PreviousPage.FindControl("txtLastName");
        Label1.Text = "Welcome " + txtPbFirstName.Text + " " + txtPbLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}
VB.NET Code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    'Check whether previous page is cross page post back or not
    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
        Dim txtPbFirstName As TextBox = DirectCast(PreviousPage.FindControl("txtFirstName"), TextBox)
        Dim txtPbLastName As TextBox = DirectCast(PreviousPage.FindControl("txtLastName"), TextBox)
        Label1.Text = ("Welcome " & txtPbFirstName.Text & " ") + txtPbLastName.Text
    Else
        Response.Redirect("Default.aspx")
    End If
End Sub

If you are using masterpages then you need to write code to FindControl as mentioned below
ContentPlaceHolder exampleHolder =(ContentPlaceHolder)Page.PreviousPage.Form.FindControl ("Content1"));
TextBox txtExample = exampleHolder.FindControl("txtFirstName");

2nd Method
Using Property to expose and Consume values of TextBox
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Html of the page needs no changes ,
C# code behind for Default.aspx
public TextBox pbTxtFirstName
    {
        get
        {
            return txtFirstName;
        }
    }

    public TextBox pbTxtLastName
    {
        get
        {
            return txtLastName;
        }
    }

VB.NET
Public ReadOnly Property pbTxtFirstName() As TextBox
    Get
        Return txtFirstName
    End Get
End Property

Public ReadOnly Property pbTxtLastName() As TextBox
    Get
        Return txtLastName
    End Get
End Property
Now to retrieve or consume exposed properties on Second page we need to add below mentioned page directive in html source of Default2.aspx page(usually at the top of page)
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
Now write this code in page_Load event of second page to retrieve values of controls
C# code
protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        Label1.Text = "Welcome " + PreviousPage.pbTxtFirstName.Text + " " + PreviousPage.pbTxtLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}
VB Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
        Label1.Text = ("Welcome " & PreviousPage.pbTxtFirstName.Text & " ") + PreviousPage.pbTxtLastName.Text
    Else
        Response.Redirect("Default.aspx")
        
    End If
End Sub

Hope this helps

20

Check All Checkbox In GridView To Bulk Edit Update ASP.NET

This example explains how to use Check All Checkbox In GridView To Bulk Edit Or Update in ASP.NET with C# and VB.NET. I have put a checkBox in header Template of gridview which on checking will check all rows in gridview using server side code to implement CheckAll CheckBox functionality.

CheckAll CheckBox In GridView to Edit and Update


Html SOURCE OF GRIDVIEW
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false" 
              CellPadding="2" ForeColor="#333333" 
              GridLines="Both" 
              DataKeyNames="ID" 
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" 
             Text='<%# Bind("Name") %>' ForeColor="Blue" 
             BorderStyle="none" BorderWidth="0px" 
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" 
             Text='<%# Bind("Location") %>' 
             ForeColor="Blue" BorderStyle="none" 
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" 
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" 
UpdateCommand="UPDATE [Details] SET [Name] = @Name, 
               [Location] = @Location WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>

<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="Location" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server" 
            OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" 
            OnClick="btnDelete_Click" 
            Text="Delete" />

C# CODE
protected void chkSelectAll_CheckedChanged
                               (object sender, EventArgs e)
{
 CheckBox chkAll = 
    (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
 if (chkAll.Checked == true)
 {
   foreach (GridViewRow gvRow in GridView1.Rows)
   {
    CheckBox chkSel = 
         (CheckBox)gvRow.FindControl("chkSelect");
    chkSel.Checked = true;
    TextBox txtname = (TextBox)gvRow.FindControl("txtName");
    TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
    txtname.ReadOnly = false;
    txtlocation.ReadOnly = false;
    txtname.ForeColor = System.Drawing.Color.Black;
    txtlocation.ForeColor = System.Drawing.Color.Black;
   }
 }
 else
 {
  foreach (GridViewRow gvRow in GridView1.Rows)
  {
   CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
   chkSel.Checked = false;
   TextBox txtname = (TextBox)gvRow.FindControl("txtName");
   TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
   txtname.ReadOnly = true;
   txtlocation.ReadOnly = true;
   txtname.ForeColor = System.Drawing.Color.Blue;
   txtlocation.ForeColor = System.Drawing.Color.Blue;
   }
  }
}

VB.NET
Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox)
    If chkAll.Checked = True Then
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = True
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = False
            txtlocation.[ReadOnly] = False
            txtname.ForeColor = System.Drawing.Color.Black
            txtlocation.ForeColor = System.Drawing.Color.Black
        Next
    Else
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = False
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = True
            txtlocation.[ReadOnly] = True
            txtname.ForeColor = System.Drawing.Color.Blue
            txtlocation.ForeColor = System.Drawing.Color.Blue
        Next
    End If
End Sub



Hope this helps.

25

Merge GridView Cells Or Columns In Row ASP.NET C# VB.NET

In this example i am going to describe how to Merge GridView Cells Or Columns In Gridview Rows Using C# and VB.NET in ASP.NET Containing Same Data or content. For this i m using DataBound Event of gridview, counting total rows and then checking each cells value against value of same cell in previous row and then setting the RowSpan of cells.

Merge GridView Cells Or Columns

For this i have created a table containing Counties ,states and respective cities and country and state cells / columns are merged in rows having same country or states.


For knowing how to merge Gridview headers read article below
Merging GridView Header Columns or multiple Headers


You would also like to read
Hide GridView Columns In Normal Mode and Visible In Edit


Running Total In Gridview Footer in ASP.NET C# VB.NET











Html source of the page look like this
<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False"  
    BorderStyle="None" BorderWidth="1px" CellPadding="4" 
    GridLines="Horizontal" ForeColor="Black" 
    Height="119px" DataSourceID="SqlDataSource1" 
    OnDataBound="GridView1_DataBound1"> 
            <Columns>
            <asp:BoundField DataField="Country" 
                            HeaderText="Country" 
                            SortExpression="Country" />
            <asp:BoundField DataField="State" 
                            HeaderText="State" 
                            SortExpression="State" />
            <asp:BoundField DataField="City" 
                            HeaderText="City" 
                            SortExpression="City" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City] 
               FROM [Details] ORDER BY [State]">
</asp:SqlDataSource>

C# code behind
protected void GridView1_DataBound1(object sender, EventArgs e)
{
  for (int rowIndex = GridView1.Rows.Count - 2; 
                                     rowIndex >= 0; rowIndex--)
  {
    GridViewRow gvRow = GridView1.Rows[rowIndex];
    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
    for (int cellCount = 0; cellCount < gvRow.Cells.Count; 
                                                  cellCount++)
    {
     if (gvRow.Cells[cellCount].Text == 
                            gvPreviousRow.Cells[cellCount].Text)
     {
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
       {
         gvRow.Cells[cellCount].RowSpan = 2;
       }
       else
       {
        gvRow.Cells[cellCount].RowSpan = 
            gvPreviousRow.Cells[cellCount].RowSpan + 1;
       }
       gvPreviousRow.Cells[cellCount].Visible = false;
    }
   }
 }
}
VB.NET code behind
Protected Sub GridView1_DataBound1
           (ByVal sender As Object, ByVal e As EventArgs)

For rowIndex As Integer = GridView1.Rows.Count - 2 To 0 Step -1
    Dim gvRow As GridViewRow = GridView1.Rows(rowIndex)
    Dim gvPreviousRow As GridViewRow = GridView1.Rows(rowIndex + 1)
    For cellCount As Integer = 0 To gvRow.Cells.Count - 1
    If gvRow.Cells(cellCount).Text = 
                         gvPreviousRow.Cells(cellCount).Text Then
    If gvPreviousRow.Cells(cellCount).RowSpan < 2 Then
    gvRow.Cells(cellCount).RowSpan = 2
    Else
    gvRow.Cells(cellCount).RowSpan = 
                       gvPreviousRow.Cells(cellCount).RowSpan + 1
    End If
    gvPreviousRow.Cells(cellCount).Visible = False
    End If
    Next
  Next
End Sub


13

SubReport In Crystal Reports

In this example i am going to describe how to Create SubReports in Crystal Reports or Crystal Reports SubReport in ASP.NET Using C# And VB.NET. For this i have used two tables from MS SQL database named Employees and Projects.
Main Crystal Report is fetching data from both the tables and is grouped by Project Name

SubReport is used to display information about respective project and fetching data from Projects Table.

Schema for both the tables in shown below in images, create tables accordingly and add relevant data in it to start.


You can click on Images to Enlarge 

 
  
To start , Create a new website in VS and right click on Solution Explorer and select Add new Item > Crystal Report. In the wizard window choose Using the Report Wizard radio button and Standard type in Choose an Expert section.

 
In next screen select Expand OLEDB(ADO) and Choose create new connection 

 
Select Microsoft OLEDB Provider for SQL server and click next 

 
In next screen check the Integrated security checkbox so that report doesn't ask for username and password  Enter you SQL Server name and Select DataBase from the dropdown ,

 
In next window expand and locate your tables you want to use and add them in right pane 

 
  
In next screen select the fields you want to display in main report and add them in right pane , in my case i am showing fields from two tables in main report 
 Now select the field which you want report to be grouped by ( in this example i m grouping report by Project Name)

Select the report style you want and finish the wizard 

 Now to add a subReport Right click in group header section (below Group #1 Name) 
Choose Insert > SubReport , Place the ractangle where you want SubReport to be displayed. a wizard window will open prompltly

 
Enter report Name and click on report wizard buttonin next screen ,
  
  
  
Choose the table and fields you want to use in SubReport in next two screens and click on finish 
Now Insert subReport window will open again , In this window click on Link Tab and select the field on which you want to filter SubReport or the ID of the record to show SubReport. I am using ProjectID in this example.

This is how design of report will look like 

 
And this is how report preview will look

 
Save , build and rum the website. 
Now if you don't want to show SubReport but want to put a hyperlink instead or want to create On-Demand SubReport then do these changes in the design of report 
Right click on SubReport in Design View and select Format Object 

 
In the window opened ,Go to SubReport tab, Change the SubReport name to text you want to show as hyperlink, Check the On-demand SubReport check box and click on ok 
 
 
Now design of report will look like image below 

 

On default.aspx page drag CrystalReportViewer from toolbox and assign CrystalReport we just created as source
Html source will go like this (AutoGenerated)
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
                        AutoDataBind="True" Height="1039px" 
                        ReportSourceID="CrystalReportSource1" 
                        Width="901px" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>

Save, build and run the solution , this is how Crystal Report SubReport will look like


Hope this helps.

Find More Articles