Displaying empty grid message in asp.net using C#

In this tutorial we will learn how to display empty grid message when grid contains no record. It is better to display a suitable message such as No Record Found when grid is empty.

In asp.net using C# it is quite easy to display empty grid message.

There is couple of ways to display empty grid message in C#. Let’s have a look over them.

Method 1)

Use EmptyDataText attribute in gridview tag if you want to show empty grid message

Let’s look over its implementation.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" HeaderStyle-HorizontalAlign="Left" HeaderStyle-VerticalAlign="Top" EmptyDataText="No Record Found" EmptyDataRowStyle-ForeColor="Maroon" EmptyDataRowStyle-HorizontalAlign="Center" GridLines="None">

Now you will get No Record Found text in Maroon Color at center align when there is no data in the grid.

Method 2)

Use <EmptyDataTemplate> after </columns> inside the <asp:GridView></asp:Gridview>

Let’s look over its implementation.

<asp:gridview id="GridView1" runat="server" width="100%">
<Columns>
<asp:TemplateField HeaderText="Email" >
<ItemTemplate>
<asp:Label ID="lbl_Email" Text='<%# Bind("User_Email")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" >
<ItemTemplate>
<asp:Label ID="lbl_first_name" Text='<%# Bind("User_First_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" >
<ItemTemplate>
<asp:Label ID="lbl_last_name" CssClass="aLinkButton" Text='<%# Bind("User_Last_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Label ID="lbl_RecordNotFound" Text="No Record Found" runat="server" Font-Size="Larger" ForeColor="maroon" ></asp:Label>
</EmptyDataTemplate>

</asp:gridview>

Now if you want to show empty grid message underneath the grid header then add table inside the <EmptyDataTemplate> according to the your gridview header, the most feasible way to show empty grid message with grid header is to right click your aspx page in the web browser (when grid contains some data), go to view source and then copy grid header code, normally grid header lie inside a table, the benefit of doing such is that if you have applied any CSS Class to gridview then that class will also be implemented automatically on the Empty Grid Message.

Let’s look over its implementation.

<EmptyDataTemplate>
<table cellpadding="2" cellspacing="2" width="100%">
<tr>
<td> Email </td><td> First Name </td><td>Last Name</td>
</tr>
<tr>
<td colspan="3" align="center">
<asp:Label ID="lbl_RecordNotFound" Text="No Record Found" runat="server" Font-Size="Larger" ForeColor="maroon" ></asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>

So these are the methods to show empty grid message when grid is empty or grid contains no record.
Read more...

Text slideshow in javascript

In this javascript tutorial we will learn how to develop text slideshow in javascript. Sometimes it become a necessary requirement to develop a text slideshow in the website so to avoid use of Flash because flash makes the webpage heavier and sometimes reader of the website don’t have any flash reader installed in web browser so its better to use javascript to develop the text slideshow.

Let’s have a look over code to understand how to implement text slideshow in javascript.

<html>

<head>

<title>Text Slideshow in javascript</title>

<script type="text/javascript" language="javascript">

var slideArray = new Array()

slideArray[0]= "Here comes the <strong>First Slide</strong>.<br> Some of text goes here ";

slideArray[1]= "<strong>Second Slide</strong>.<br> Some of text goes here ";

function firstSlide()

{

document.getElementById('div_display').innerHTML=slideArray[0];

setTimeout("secondSlide()",10000);

}

function secondSlide()

{

document.getElementById('div_display').innerHTML=slideArray[1];

setTimeout("firstSlide()",10000);

}

</script>

</head>

<body>

<table width="100%" cellpadding="2" cellspacing="2">

<tr>

<td>

<div id="div_display"><script type="text/javascript" language="javascript">firstSlide();</script></div>

</td>

</tr>

</table>

</body>

</html>

Now it’s turn to understand the code.

First of all I have made an array and give it a name slideArray and put two elements in this array. Then I made a javascript function to display first array element, I give firstSlide() name to that javascript function. In this function I am assigning the first array element to the div so that it can be display in the div then I use built-in javascript function setTimeout() function that will redirect focus to the secondSlide() function so that second slide can also be displayed after ten seconds. Yeah you are right, 10000 means ten seconds delay.

Now let’s suppose a case in which you have five slides to display and you want to display them randomly. Let’s look on how to do this

<script type="text/javascript" language="javascript">

var slideArray = new Array()

slideArray[0]= "Here comes the <strong>First Slide</strong>.<br> Some of text goes here ";

slideArray[1]= "<strong>Second Slide</strong>.<br> Some of text goes here";

slideArray[2]= "<strong>Third Slide</strong>.<br> Some of text goes here";

slideArray[3]= "<strong>Fourth Slide</strong>.<br> Some of text goes here";

slideArray[4]= "<strong>Fifth and Final Slide</strong>.<br> Some of text goes here ";

function textSlideShow()

{

var total_slides;

total_slides=Math.floor(Math.random()*slideArray.length)

document.getElementById('div_display').innerHTML=slideArray[total_slides];

setTimeout("textSlideShow()",10000);

}

</script>

And then call this javascript function inside the div element in which you want to display text slideshow like below.

<div id="div_display"><script type="text/javascript" language="javascript"> textSlideShow();</script></div>

Every time you will get random slide.

Now let’s suppose a case in which you want to show text coming from database in slideshow rather than static text.

First of all use any web programming language such as php, asp.net, asp to get data from database and then assign that data to different textboxes and hide these textboxes then do this to get data from textbox and use that data as a text in slideshow.

<html>

<head>

<title>Text Slideshow in javascript</title>

<script type="text/javascript" language="javascript">

var slideArray = new Array()

var myName,myAge;

function firstSlide()

{

myName=document.getElementById('txt_Name').value;

slideArray[0]=myName;

document.getElementById('div_display').innerHTML=slideArray[0];

setTimeout("secondSlide()",10000);

}

function secondSlide()

{

myAge =document.getElementById('txt_Age').value;

slideArray[1]=myAge;

document.getElementById('div_display').innerHTML=slideArray[1];

setTimeout("firstSlide()",10000);

}

</script>

</head>

<body>

<table width="100%" cellpadding="2" cellspacing="2">

<form name="form1">

<tr>

<td>

<input type="text" id="txt_Name" style="display:none;" value="Hello"><br>

<input type="text" id="txt_Age" style="display:none;" value="Hello2">

<div id="div_display"><script type="text/javascript" language="javascript">firstSlide();</script></div>

</td>

</tr>

</form>

</table>

</body>

</html>

So these are the different methods that you can use to develop text slideshow in javascript. I hope you like this article.

Happy Coding…!

Read more...

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>)

Once I was working in master page and wanted to call the javascript function that contains Code Blocks. Every time I got this error The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>). I was feeling headache to solve that error then one of my friend told me solution to get rid of this error and then every thing gone fine.

Actually I had an asp textbox control and an aspx button control in my masterpage, I wanted to get the value of <asp:TextBox id="txt_Name" runat="server"> in my javascript function but every time I got that error then I cut my javascript function from <head> </head> and put it into <form name="form1" runat="server"> of master page and then every thing worked fine.

You just have to put your javascript function in the form tag of master page

Here’s my javascript function

<form id="form1" runat="server">
<script type="text/javascript" language="javascript">

function FormValidation()
{
var my_Var;
my_Var=document.getElementById('<%=txt_Name.ClientID %>').value;

if(my_Var=="")
{
alert("Please enter the name");
return false;
}
else
{
return true;
}

}
</script>
</form>

Note:- The form attribute must contain runat="server" attribute.

So this is the way to avoid The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>) error.

Happy Coding!

Read more...

How to find the div in javascript

In this javascript tutorial we will learn how to find the div that we want to find. Once during coding it became a necessary requirement for me to find a specific div, I use below mentioned code to find that div, actually I want to execute another javascript function if specific div found else nothing should be executed.

So let's have a look on how to find the div in javascript.

<script language="javascript" type="text/javascript">
function findingDiv()
{
Div_Collection = document.getElementsByTagName("div");
for (i=0;i<Div_Collection.length;i++)

{
if(Div_Collection[i].getAttribute("id") == "my_div")
{

Myfunc();

}
else
{
}
}
}
</script>

Now it’s up to you and up to condition where u will call this function. In this function first of all I get all div elements and store these div elements in a Div_Collection variable that is actually playing role as an array. It’s necessary that there must be some unique thing in the div that you are going to be find, I assigned a unique ID to the div that I am going to find. In my case that div ID is my_div. After that I apply for loop on the array and then search for that specific div by ID. If that div found then I am executing another function else nothing.

So this is the way to find the div in javascript. I hope you like this javascript tutorial.


Note:- You can also find elements other than div using this javascript technique Read more...

Counting words in a textarea using javascript

In this javascript tutorial we will learn how to count the number of words entered in a textarea using javascript. Let's have a look over below mentioned code that demonstrates how to count the words entered in a textarea using javascript.

<script language="javascript" type="text/javascript">

function counting_words(txt_Name)
{

var number_of_words;
number_of_words=txt_Name.value.split(" ");

alert("Textbox has "+number_of_words.length+" words");

return false;

}

Now here's the code that will made textarea in your webpage.

<form name="form1">
<textarea name="details"> </textarea>
<input type="submit" value="Check" onclick="return counting_words(document.form1.details)"></form>

Now when you will entered the words in textarea and then press submit button then an alert will come that will show you how many words you have entered in the textrea.

So this is the way to count words in a textarea using javascript.
Read more...

Checking of empty and null string in asp.net using C#

In this tutorial we will learn how to check the empty string and null string in asp.net using C#. But before moving forward let’s understand what is the difference between null string and empty string.

Null String:-
A string is said to be a Null String if it hasn’t been assigned any value yet.

Empty String:-
A string is said to be an Empty String that has been assigned an empty value.

Empty and null string is different and we must differentiate between them.

You may get error if you want to check the certain property of the string i.e; length of the string then you may get error if that string is NULL because we can’t get the length of Null String. So it’s better to check the string before applying any function over it. In this tutorial we will learn how to detect empty string as well as null string in asp.net using C#.

Now let’s consider we have a textbox in .aspx web page suppose we have
<asp:TextBox ID="txt_Name" runat="server"></asp:TextBox> in our .aspx webpage now on Button’s OnClick event we are going to check whether txt_Name contains empty/Null value or not.

Methods to check the empty string:-

In this section we will learn different techniques to detect the empty string in asp.net using c#

Check_empty_null_string.aspx.cs

Method 1
if (txt_Name.Text.ToString().Equals(""))
{
lbl_message.Text="Contains Empty value";
}

Method 2
if (txt_Name.Text.ToString().Length == 0)
{
lbl_message.Text="Contains Empty value";
}

Method 3
if (txt_Name.Text.ToString().Equals(""))
{
lbl_message.Text="Contains Empty value";
}

Methods to check the null string:-

if (txt_Name.Text.ToString() == null)
{
lbl_message.Text="Contains Null value/ Null string";
}

Sometimes you may get error like this Object reference not set to an instance of an object when you intend to get any property of the string but that string is null, so it’s better to check the empty string as well as null string in one statement to make code as short as you can ant to make application more free.

Methods to check the null string and empty string in one statement

Method1
if (string.IsNullOrEmpty(txt_Name.Text.ToString()))
{
lbl_message.Text="Contains Empty value or Null Value";

}

Method2
if(txt_Name.Text.ToString()!=null && txt_Name.Text.ToString()!=string.Empty)
{
lbl_message.Text="String is neither empty nor null";
}

You can also check the existence of empty string or null string by applying the above mentioned methods over the values coming from database.

So this is the way to check and detect the empty and null string in asp.net using c#.



Read more...

Updation of records in asp.net using C#

In this tutorial we will learn how to perform the updation of records in asp.net using C#. First of all we will show all records coming from database in gridview and then using gridview’s built-in event RowEditing we will perform updation of records in asp.net using C#. To perform editing/updation of records in asp.net using C# is quite easy.

 

editing_records_in_gridview.aspx

<asp:gridview id="GridView1" runat="server" width="100%">

<Columns>

<asp:TemplateField HeaderText="ID" >
<ItemTemplate>
<asp:Label ID="lbl_UserID" Text='<%# Bind("User_ID")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" >
<ItemTemplate>
<asp:Label ID="lbl_Email" Text='<%# Bind("User_Email")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" >
<ItemTemplate>
<asp:Label ID="lbl_first_name" Text='<%# Bind("User_First_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" >
<ItemTemplate>
<asp:Label ID="lbl_last_name" CssClass="aLinkButton" Text='<%# Bind("User_Last_Name")%>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="15px" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Delete" >                       

<ItemTemplate>

<asp:Label ID="lbl_delete" Visible="false"  Text='<%# Bind("User_ID")%>' runat="server"></asp:Label>                        

<asp:ImageButton runat="server" ID="img" ImageUrl="images/b_drop.png" CommandName="Delete"  />

</ItemTemplate>                        

</asp:TemplateField>
</Columns>
</asp:gridview>

editing_records_in_gridview.aspx.cs

using System;

using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;


public partial class Tutorials_editing_records_in_gridview : System.Web.UI.Page
{
string strcon = "server=localhost;database=tutorials-db; uid=adeel;password=pakistan; Connect Timeout=200; Max Pool Size=5000"; 

SqlConnection con = new SqlConnection(); 

SqlCommand com = new SqlCommand(); 

DataSet ds = new DataSet(); 

SqlDataAdapter da; 

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
} 

private void bindgrid()
{
ds.Clear();
con.ConnectionString = strcon; 

com.Connection = con;

con.Open();

string strQuery = "select * from users"; 

da = new SqlDataAdapter(strQuery,con);

da.Fill(ds); 

GridView1.DataSource = ds;

GridView1.DataBind();

con.Close();
}

 

//Editing of records in asp.net using C#

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        int index = e.NewEditIndex;

        GridViewRow row = GridView1.Rows[index];

        Label lbl = (Label)row.FindControl("lbl_edit");

        string id = lbl.Text;

        Response.Redirect("edit_records.aspx?UserID="+id+"");

 

    }

// Editing of records function ends here

}

 

edit_records.aspx

   <table>

        <tr>

            <td>

                Email

            </td>

            <td>

                <asp:TextBox ID="txt_Email" runat="server" EnableTheming="False"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                First Name

            </td>

            <td>

                <asp:TextBox ID="txt_FirstName" runat="server" EnableTheming="False"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

                Last Name

            </td>

            <td>

                <asp:TextBox ID="txt_LastName" runat="server" EnableTheming="False"></asp:TextBox>

            </td>

        </tr>

        <tr>

            <td>

               

            </td>

            <td>

                <asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />

            </td>

        </tr>

    </table>

 

edit_records.aspx.cs

 

public partial class Tutorials_edit_records : System.Web.UI.Page

{

string strcon = "server=localhost;database=tutorials-db; uid=adeel;password=pakistan; Connect Timeout=200; Max Pool Size=5000";     SqlConnection con = new SqlConnection();

    SqlCommand com = new SqlCommand();

    DataSet ds = new DataSet();

    SqlDataAdapter da;

    string UserID;

 

    protected void Page_Load(object sender, EventArgs e)

    {

        UserID = Request.QueryString["UserID"].ToString();

 

        if (!IsPostBack)

        {

            string strQuery = "select User_Email,User_First_Name,User_Last_Name from users where User_ID='" + UserID + "'";

            con.ConnectionString = strcon;

            com.Connection = con;

            com.CommandText = strQuery;

            con.Open();

            SqlDataReader rdr = com.ExecuteReader();

            while (rdr.Read())

            {

                txt_Email.Text = rdr.GetValue(0).ToString();

                txt_FirstName.Text = rdr.GetValue(1).ToString();

                txt_LastName.Text = rdr.GetValue(2).ToString();

            }

            con.Close();

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        UserID = Request.QueryString["UserID"].ToString();

        string strUpdateQuery = "update users SET User_Email='" + txt_Email.Text + "', User_First_Name='" + txt_FirstName.Text + "', User_Last_Name='" + txt_LastName.Text WHERE User_ID='" + UserID + "'";

        con.ConnectionString = strcon;

        com.Connection = con;

        com.CommandText = strUpdateQuery;

        con.Open();

        com.ExecuteNonQuery();

        con.Close();

 

    }

}

So this is the way to perform editing of data/records in asp.net using C#

Happy Coding, Keep Coding…!

 

 

Read more...