Wednesday, August 26, 2009

Default Submit Button

When developing the desktop application it is very common that you set the default accept and cancel button for the window form. So that if user click the enter key then action take place like submission of the inputs entered by the user or other actions and when user click the esc key then the form close. In window form , form has two properties called accept button and cancel button which are used for this purpose. But when you want to give this type of functionality in the web application then there is little difference and more ways that you can give this functionality. In this post I will show you how you can give this functionality to user.

First Way
With the release of the ASP.NET 2.0, the problem of making the default button is much easier with the introduction of the "default button" property of the form. Now defaultbutton attribute can be used with <form> or <asp:panel> control. What button will be "clicked" depends of where actually cursor is and what button is chosen as a default button for form or a panel.Here is sample HTML code that contains one form and one panel control:

<form defaultbutton="buttonID" runat="server">
With the above html code you can set the default button for the form or to the panel control. In default button property you have to mention the ID of the button control which is used as the default button when enter key is pressed on the form or on the panel control.

Second Way
In the second of achieving default button functionality is the JavaScript way and below is the JavaScript code which is used to set the default button for the page. Here I have a simple function named "DefaultButton" which will return Boolean value of true or false depending on the
the value of the keycode, if 13 which is used as the enter key value, it will call the click event of the button which is set as the default button and return false else it will return true.
function DefaultButton()
if(event.which || event.keyCode)
if ((event.which == 13) || (event.keyCode == 13))
return false;
return true;
The default button function is registered against the onkeypress JavaScript of the form, So that keypress while focusing on any of the control on the form it will raise the click event of the button when the user click the enter key. You have to registered only one keypress event for the form no need to right code for every input control when they are in focus and has to manage the enter key for there own. You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Tuesday, August 25, 2009

Fixed GridView Header Using CSS

In this post I will show you how you can fix the header of the grid so if user scroll down then the header will be in the view. Here is out of my example page and you can see that I have scroll down the grid and the grid header is in view so the user can see header text as he/she scroll down the grid.

And here is the my Css which is used to format the header of the grid in this Css class which is named GridHeader. The property which is used to fixed the position of the grid header is the Position property which has value relative.

background-color: #738AAD;
border-bottom: 1px solid #00347B;
color: #FFFFFF;
font-weight: bold;
padding-left: 2px;
padding-top: 2px;
text-align: left;
position:relative ;

You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Saturday, August 22, 2009

Returning Multiple Values From ModalDialog

In this post I will show you how you can call the showModalDialog to open the modal dialog and then how you can pass back the multiple values from the modal dialog. For this example I have two form one which is the main form and the second one is the modal dialog form which will be used to take the user input, I have only two field on modal dialog form the user name and the password and these two fields are return to the main form from the modal dialog form. In the main form I have only one button which is used to open the modal dialog and there label one to show the success or failure of the return value and the other two labels to show the user name and the password if user entered on the modal dialog. Here is my JavaScript which is used to open modal dialog and then check for the return values.

function OpenWindow()
var sFeatures ='dialogHeight=400px; dialogWidth=600px;center:yes;help:no;status=yes,toolbar=no,menubar=no';
var ErrorMessage = document.getElementById('lblErrorMessage');
var UserName= document.getElementById('lblUserName');
var Password = document.getElementById('lblPassword');
var returnValue=window.showModalDialog("frmModalDialog.aspx", '', sFeatures);

if(returnValue != null)
ErrorMessage .innerHTML='User Entered Values:';
ErrorMessage.innerHTML='User didn\'t enter any value:';
UserName.innerHTML=' ';
Password.innerHTML=' ';
return false;
Here is the syntax of the showModalDialog function. In the syntax of the show modal dialog the parameter which are enclosed in [ and ] are optional you can omit these parameters.

vReturnValue = object.showModalDialog(sURL [, vArguments] [, sFeatures])

Here is the detail of the parameter to the showModalDialog function.
  1. sURL:Required. String that specifies the URL of the document to load and display.
  2. vArguments:Optional. Variant that specifies the arguments to use when displaying the document. Use this parameter to pass a value of any type, including an array of values. The dialog box can extract the values passed by the caller from the dialogArguments property of the window object.
  3. sFeatures:String that specifies the window ornaments for the dialog box, using one or more of the following semicolon-delimited values:
Returns the value of the returnValue property as set by the window of the document specified in sURL, and type of the return value is Variant.
Here the JavaScript on the show modal form which is used to return value from the modal dialog. Here I have two function PassValuesBack and the CanclClick function. In the PassValueBack function which is bind with the sign in button and used to return value to the calling form. I have searched the txtLoginName and the txtPassword button and save them in the local variable so that there value can be send back to the calling form. Then I have created object and added LoginName and Password properties to that object and after assigning the user name and password to these properties respectively I have assign this object to the returnValue and close the window. In the CancelClick I have assign null to the returnValue and close window.
function PassValuesBack()
var txtLoginName= document.getElementById ('txtLoginName');
var txtPassword = document.getElementById('txtPassword');
var objReturnValue = new Object();
objReturnValue.LoginName =txtLoginName.value;
objReturnValue.Password = txtPassword.value;
window.returnValue = objReturnValue;

function CancelClick()
window.returnValue = null;

Now on the main form If user entered values and press sign in button then it will return values of the user login name and password, even if user didn't entered anything and press sign in button then the empty string is returned. On main form I have check for the null value of the returned variable, mean if user click on the close button on the modal dialog or click the cancel button then it will execute the else statement but if the return object is not null then get the value and assign to the label controls. You can download the source code from here.

  1. Show Modal Dialog Method
All and any comments / bugs / suggestions are welcomed!

Saturday, August 15, 2009

Populate dropdown based on selection of other dropdown in ASP.NET Using Jquery Json

I have used the Json technique to retrieve the server side records on the client side in my post Using Json in Application, where I have explain how you can retrieve json data. Now here in this post i will use same example which is used in that post and show you how you can use the json of the jquery.For detail of the example you can visit my Using Json in Application,post , here I will explain the JavaScript I have used to retrieve the values of the second dropdown list control. Here is my JavaScript code. In the code below I just bind the change event to the ddlRegion dropdown list control which also act as parent control. In the change event of the region dropdown list control, I have save the value of the region which is the id of the region and then build the url which consist of the page name plus the regionID and the sid as query string parameters.
var regionID = this.value;

var url="ResponsePage.aspx";
url=url+"?regionID="+ regionID;

$.getJSON(url, function(returnDataCollection)
$("#ddlTerritory")[0].innerHTML ='';
for(var intCounter=0; intCounter < returnDataCollection.length-1; intCounter++)
$("#ddlTerritory").append($("<option></option>").val(returnDataCollection[intCounter].TerritoryID ).html(returnDataCollection[intCounter].TerritoryDescription));

Next is the call to the $.getJSON function and here is the syntax of the $.getJSON function.
 $.getJSON(url[, data][, success]) 
Here are the detail of the parameter list which are passed to the function.
  • url: A string containing the URL to which the request is sent
  • data: (optional): A map of data that is sent with the request
  • success: (optional): A function that is executed if the request succeeds
And $.getJSON function return the XMLHttpRequest object that was created.The callback is passed the returned data, which will be a JavaScript object or array as defined by the JSON structure and parsed using the eval() function. Then in the success function I have loop through the array collection and add the values in the next dropdownlist control.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Saturday, August 8, 2009

Merge GridView Cells Or Columns in Row ASP.NET C#

During writing of my last post on the Custom Pager for GridView Control I have found very interesting article on merging the cells of the grid view control. In this post I will continue my work of Custom Pager for GridView Control, and extend it to merge the cells of the gridview control. I have used same source example of the Custom Pager for GridView Control post.
Here is the code which is used to merge the cell of the grid view control after the grid view control is filled with data, the code below is written in the databound event of the grid view control.

for (int intRowIndex = grdvCustomer.Rows.Count - 2; intRowIndex >= 0; intRowIndex--)
GridViewRow gvCurrnteRow= grdvCustomer.Rows[intRowIndex];
GridViewRow gvPreviousRow = grdvCustomer.Rows[intRowIndex + 1];
for (int intCellCount = 0; intCellCount < gvRow.Cells.Count; intCellCount++)
if (gvCurrnteRow.Cells[intCellCount].Text == gvPreviousRow.Cells[intCellCount].Text)
if (gvPreviousRow.Cells[intCellCount].RowSpan < 2)
gvCurrnteRow.Cells[intCellCount].RowSpan = 2;
gvCurrnteRow.Cells[intCellCount].RowSpan = gvPreviousRow.Cells[intCellCount].RowSpan + 1;
gvPreviousRow.Cells[intCellCount].Visible = false;
In the above code the logic of merging the cells is simple one. The for loop start from the second last row of the grid. Next is to declare the two GridViewRow objects by storing the second last and the last row from the grid view rows. Next is to compare the text of both the row and if the text both rows are equal then check the if the rowspan of the gvCurrentRow if it is less then 2 then assign it to 2 and if it is greater then 2 then assign the rowspan plus 1 of the previous row to the gvCurrentRow object and at the end set visible property of the gvpreviouse object to false.You can download the source code from here.

1- Merge GridView Cells Or Columns in Row ASP.NET C# VB.NET

All and any comments / bugs / suggestions are welcomed!

Calculating network bandwidth speed in C#

In this post I will tell you how to use the C# language to calculate the bandwidth. Here is my simple form which is used to display information about the network bandwidth speed. For this example I have only label controls on my form and one Timer control which is used to update the status of the network bandwidth after every second.

First here is the code which i have used to get the local area connection object from the GetAllNetworkInterfaces function and is a member function of the NetworkInterface class which Provides configuration and statistical information for a network interface. This class encapsulates data for network interfaces, also known as adapters, on the local computer. You do not create instances of this class; the GetAllNetworkInterfaces method returns an array that contains one instance of this class for each network interface on the local computer. In the default construct of the form, I have used the foreach loop to get the local area connection network interface. I have matched the name of the networkInterface and when it is found I have place it in the class variable so that I can used it later.
foreach (NetworkInterface currentNetworkInterface in NetworkInterface.GetAllNetworkInterfaces())
if (currentNetworkInterface.Name.ToLower() == "local area connection")
networkInterface = currentNetworkInterface;
Here is the code which is called every tick of the time and used to update the label to show the internet status. Here in the first statement I have used the GetIPv4Statistic function of the network interface class , which will return the object of IPv4InterfaceStatistics class.From that object, we can fetch the BytesSent and BytesReceived from that network interface. By creating a simple timer that handles each tick rate in each 1sec interval, we can find the speed of bytes per second by finding the difference between the new bytes with respect to the previous ones. To make it more readable, we could convert bytes into kilobytes by dividing by 1024.

IPv4InterfaceStatistics interfaceStatistic = networkInterface.GetIPv4Statistics();

int bytesSentSpeed = (int)(interfaceStatistic.BytesSent - lngBytesSend) / 1024;
int bytesReceivedSpeed = (int)(interfaceStatistic.BytesReceived - lngBtyesReceived) / 1024;

lblSpeed.Text = (networkInterface.Speed / 1000000).ToString() + " Mbps";
lblPacketReceived.Text = interfaceStatistic.UnicastPacketsReceived.ToString();
lblPacketSend.Text = interfaceStatistic.UnicastPacketsSent.ToString();
lblUpload.Text = bytesSentSpeed.ToString() + " KB / s" ;
lblDownLoad.Text = bytesReceivedSpeed.ToString() + " KB / s ";
lngBytesSend = interfaceStatistic.BytesSent;
lngBtyesReceived = interfaceStatistic.BytesReceived;
After the calculation of the upload and download speed, the new values of the bytesSend and bytesReceived are save in the class variable so that next time these variable are used to calculate the upload and download speed.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Sunday, August 2, 2009

Fetching Comma Separated Value In One Column MSSQL

In this example i am going to describe how to combine multiple records in a column in MS SQL into one record comma separated.I have used the customer table of the northwind database. What I want to do is to get the Country name in one column and then in the second column I want to have company names separated by the comma. Here is the output of the simple select statement.
And here is the out put of the desired result.

Here is the script used to produce the comma separated values. Here I have first declared the local variable which is used to save the comma separated values and I have set the length of the variable to 1000, you can change it to your desired capacity. In the next statement I have used the @EmployeeNames variable to store the Comma separated value. And I have used the Coalesce function which is used to returns the first nonnull expression among its arguments.
Declare @EmployeeNames VARCHAR(1000)
Select @EmployeeNames=Coalesce(@EmployeeNames,'') + CompanyName +';' from Customers where country='UK'
Select distinct Country,@EmployeeNames As CompanyName from Customers where Country='UK'

And at the end I have used the simple select statement to fetch the record with the same where clause which is used in assigning the @EmployeeNames variable.

All and any comments / bugs / suggestions are welcomed!

Saturday, August 1, 2009

Custom Pager for GridView Control

When I have posted my post on the paging of the record on the sql server side, using the store procedure , I then decided to use that paged data in one of the web application. So I develop a small application to display the page data on the grid view control. During the development of the small application I have design the custom paging for the grid view control and I want to share this custom paging with all of you , So lets start with the small application.
For this example I have grid view control and I have set the visible property of the Pager to false, so the pager of the grid view is not shown to the user. Next is the custom pager for the grid view control which consist of the four image button First, last, next and previous and one label to show the current page number.

For this example code I have modified the store procedure used in the my post, so that I can get the number of records from the store procedure and display total number of page to user and also to perform action when user reaches on the last page.
Here is the main function which is used to control all the databinding and also control the paging as well, this code is taken from the GridBinding function. In the first statement of the function is the declaration of the SqlConnection object and passing the connection string to the connection object,I have passed the connection string directly to the SqlConnection object you can place your connection string to web.config on in a common place where all of you web application can access the connection string. Next is the declaration of the SqCommand object, the SqlCommand object is declared with zero (0) parameter constructor and then following are the properties set for the SqlCommand object.
  1. Connection Property
  2. CommandText
  3. CommandType
As I am using store procedure here for this example, so I have set the CommandText to the name of the store procedure and assign CommandType property the StoredProcedure enum constant.
SqlConnection getCustomerConnection = new SqlConnection("Server=ServerName; DataBase=northwind; uid=username; pwd=password");

SqlCommand getCustomerCommand = new SqlCommand();
getCustomerCommand.Connection = getCustomerConnection;
getCustomerCommand.CommandText = "getCustomer";
getCustomerCommand.CommandType = CommandType.StoredProcedure;

getCustomerCommand.Parameters.AddWithValue("@PageNumber", PageNumber);
getCustomerCommand.Parameters.AddWithValue("@PageSize", grdvCustomer.PageSize);
SqlParameter totalRecordParameter = new SqlParameter("@TotalRecord", SqlDbType.Int);
totalRecordParameter.Direction = ParameterDirection.Output;

SqlDataAdapter getCustomerDataAdapter = new SqlDataAdapter();
getCustomerDataAdapter.SelectCommand = getCustomerCommand;
DataSet dtsCustomer = new DataSet();
getCustomerDataAdapter.Fill(dtsCustomer, "Customer");

grdvCustomer.DataSource = dtsCustomer.Tables["Customer"];
TotalPages = Convert.ToInt32(getCustomerCommand.Parameters["@TotalRecord"].Value.ToString());
After assigning the Connection, CommandText and CommandType properties of the SqlCommand Object, next is to add the parameter and their values, The first parameter is the @PageNumer, which is used to get the records for the value passed, Second parameter is the @PageSize , in this case I am passing the value of the PageSize property of the grid view control. And the last parameter which is @TotalRecord , this parameter has direction to output and is used to calculate the number of pages. Next is the declaration of the SqlDataAdatper object which is used to fill the DataSet, after the declaration and initialization of the sqlDataAdapter the SelectCommand of the SqlDataAdapter is assign the SqlCommand object which is declare before. After that DataSet object is declared and initialized and in the next statement the dataset is filled and "Customer" is passed as table name. After the fill of the dataset, DataSource property of the grid view control is assign the Customer table of the dataset.
After databind of the grid view control is the assignment of the total records to the TotalPage property and here is the code of the TotalPage property. In the Property it is only used to calculate the total pages by dividing the PageSize propery of the grid view control. Here you can see if the reminder of the TotalRecord and PageSize is not equal to zero(0) then it will increament the page size by one.
int intTotalPages = 1;
if (ViewState["TotalPages"] != null)
int.TryParse(ViewState["TotalPages"].ToString(), out intTotalPages);
return intTotalPages;
int intTotalPage = value /grdvCustomer.PageSize ;
if (value % grdvCustomer.PageSize != 0)
ViewState.Add("TotalPages", intTotalPage);
lblShowingPage.Text = PageNumber + " of " + intTotalPage;
After the TotalPages property call is the function which is used to enable, disabled the first, previous, next and last image button depending on the value of the PageNumber property and the TotalRecords property. The code behind the first, previous, next and the last image button is simple , where the PageNumber property is changed and the GridBinding function is called.

You can download the source code from here.

Note: In the source I have place the script of the GetCustomer store procedure place execute this script in the nortwind database. And replace the alter key work to the create key work so that new store procedure will be created.

All and any comments / bugs / suggestions are welcomed!