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.

Find More Articles