Pages

Thursday, 25 April 2013

How to avoid Maxlength of Multiline textbox in asp.net


Introduction

In almost all web projects, we require a multiline TextBox control. It was annoying to find that the maxLength property doesn't work on multiline textboxes. There are various solutions suggesting to use validator controls to validate length. I suggest that we should put a validator as well as extend our control so that the user will not be able to enter characters more than the length specified.

Extending the TextBox

To achieve this, I tried extending the ASP.NET TextBox WebControl.

//c#
using System;
 using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
 using System.Web.UI.WebControls;
namespace CustomServerControls
 {
 /// /// Summary description for CustomServerControls ///
[DefaultProperty("Text")] [ToolboxData("<{0}:TextArea runat=server></{0}:TextArea>")] public class TextArea : TextBox
{
public override TextBoxMode TextMode
{
get { return TextBoxMode.MultiLine; }
 }

protected override void OnPreRender(EventArgs e)
{
if (MaxLength > 0)
{
 if (!Page.ClientScript.IsClientScriptIncludeRegistered("TextArea"))
{
Page.ClientScript.RegisterClientScriptInclude("TextArea", ResolveClientUrl("~/textarea.js"));
 }
this.Attributes.Add("onkeypress", "LimitInput(this)");
this.Attributes.Add("onbeforepaste", "doBeforePaste(this)");
this.Attributes.Add("onpaste", "doPaste(this)");
 this.Attributes.Add("onmousemove", "LimitInput(this)");
 this.Attributes.Add("maxLength", this.MaxLength.ToString());
}
base.OnPreRender(e);
 }
}
}

Now our custom control is ready to use. In the above code block, it should be self-explanatory that if I find the TextBox's TextMode property to be MultiLine, I add custom JavaScript and a property to pass the maxLength on the client side. I take advantage of ClientScript to attach a JavaScript, only one per page. I chose to include JavaScript as an external file because this allows us to modify the JavaScript easily. In addition, the page will not be bloated and the script will be cached.

I created this control in a Project Library so that I can use this control in any of our projects

Java Script File
doBeforePaste(control)
{
maxLength = control.attributes["maxLength"].value;
if (maxLength)
{
event.returnValue = false;
 }
 }

function doPaste(control)
{
maxLength = control.attributes["maxLength"].value;
value = control.value;
 if (maxLength)
{
event.returnValue = false;
maxLength = parseInt(maxLength);
var o = control.document.selection.createRange();
var iInsertLength = maxLength - value.length + o.text.length;
var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
o.text = sData;
}
 }

 function LimitInput(control)
{
if (control.value.length > control.attributes["maxLength"].value)
{
control.value = control.value.substring(0, control.attributes["maxLength"].value);
}
 }

Now I created a test web page and added the control on the page as:

Aspx page
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %> <%@ Register TagPrefix="Custom" Namespace="CustomServerControls" %>

Thursday, 18 April 2013

how to get string value from stored procedure

This article discusses how to return data from stored procedures: returning result sets (SELECT statements), using output variables and using the RETURN statement.  Each example includes client-side code (ASP.NET) and server-side code (T-SQL) to read the results.
 
Result Sets
 
Result sets are what you get when you run a simple SELECT statement inside a stored procedure. Let's suppose you want a stored procedure to return a list of all the people with a given message.  The code for the stored procedure might look like this:
 
USE [Test]
GO
/****** Object:  StoredProcedure [dbo].[GetSamples]    Script Date: 04/19/2013 11:58:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROC [dbo].[GetSamples](@Id INT)
AS
  BEGIN
      DECLARE @Message VARCHAR(250)

      IF EXISTS(SELECT *
                FROM   sample
                WHERE  id = @Id)
        BEGIN
            SELECT *
            FROM   sample
            WHERE  id = @Id

            SET @Message='record already exist'

            SELECT @Message
            return -- ***************change
        END
      ELSE
        BEGIN
            SET @Message='record does not exist'

            SELECT @Message
            return -- ***************change
        END
  END

Web Side

If you want to write a web page that calls this stored procedure and processes the results that code you'll need to add a using clause for the SqlClient namespace.  This is needed for all the client side samples.


 string returnValue = "";
            DataTable dt = new DataTable();
            try
            {
                string strconn = ConfigurationManager.ConnectionStrings["strconn"].ConnectionString;
                using (SqlConnection SqlConn = new SqlConnection(strconn))
                {
                    using (SqlCommand SqlComm = new SqlCommand("GetSamples", SqlConn))
                    {
                        SqlComm.CommandType = CommandType.StoredProcedure;
                        SqlComm.Parameters.AddWithValue("@Id", 1);
                        SqlConn.Open();
                        string Message_ = Convert.ToString(SqlComm.ExecuteScalar()); // this will give you message
                        SqlConn.Close();
                    }
                }
            }
            catch (SqlException ex)
            {
            }
            catch (Exception ey)
            {
            }