Wednesday, July 28, 2010

Enable/Disable Button Based On Empty TextBoxes Using JavaScript

Add this script to the page

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

function SetButtonStatus(sender, target)

{

if ( sender.value.length >= 12 )

document.getElementById(target).disabled = false;

else

document.getElementById(target).disabled = true;

}

script>

<asp:TextBox ID="txtText" runat="server" onkeyup="SetButtonStatus(this, 'btnButton')">asp:TextBox>

<asp:Button ID="btnButton" runat="server" Text="Button" Enabled="false" />

This JavaScript validates the textbox and enables the button only if the textbox contains 12 characters.

Set Focus to Textbox in Gridview inside Update Panel

Let’s see how to set focus to textbox inside Gridview inside Update Panel.

So the Gridview is designed something like this..

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:GridView ID="gvattend" runat="server" CellPadding="5"

AutoGenerateColumns="false" AllowPaging="true" PageSize="50"

GridLines="none" HeaderStyle-CssClass="tableheadbg" BorderStyle="solid" RowStyle-CssClass="nestedtable" AlternatingRowStyle-CssClass="nestedtable1"

BorderColor="#a3b4a0" BorderWidth="1px" Width="100%" TabIndex="6" >

<Columns>

<asp:TemplateField HeaderText="Marks Obtained" >

<ItemTemplate>

<asp:Textbox id="txtmarksobtain" runat="server" Width="150" AutoPostBack="true" OnTextChanged=" txtmarksobtain _TextChanged" >asp:Textbox>

ItemTemplate>

asp:TemplateField>

<asp:TemplateField HeaderText="Percentage" >

<ItemTemplate>

<asp:Textbox id="txtpercentage" runat="server" Width="150" Enabled="false" >asp:Textbox>

<asp:CompareValidator ID="cmp3" runat="server" ControlToValidate="txtpercentage" Operator="DataTypeCheck" Type="Double" ErrorMessage="Enter Numeric Value Alone" Display="dynamic" ValidationGroup="subject">asp:CompareValidator>

ItemTemplate>

asp:TemplateField>

Columns>

<EmptyDataTemplate>

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

<tr><td align="center" valign="middle" ><span class="redcolor">No Data Foundspan> td>tr>

table>

EmptyDataTemplate>

<RowStyle CssClass="nestedtable" />

<HeaderStyle CssClass="tableheadbg" />

<AlternatingRowStyle CssClass="nestedtable1" />

asp:GridView>

ContentTemplate>

asp:UpdatePanel>

And in the Code Behind:

Protected Sub txtmarksobtain _TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtmaxmarks.TextChanged

For Each gv As GridViewRow In gvattend.Rows

Dim txtmarksobtain As TextBox = DirectCast(gv.FindControl("txtmarksobtain"), TextBox)

If txtmarksobtain.Text = "" Then

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "selectAndFocus", "$get('" + txtmarksobtain.ClientID + "').focus();$get('" + txtmarksobtain.ClientID + "').select();", True)

End If

Next

End Sub

And thus focus is set to textbox inside Gridview

Saturday, July 24, 2010

Prevent Flicker from CollapsiblePanelExtender on PageLoad

Let’s see how to fix the flickering of the CollapsiblePanelExtender when collapsed is set to true (Collapsed="true")

Here is my CollapsiblePanelExtender

<cc1:CollapsiblePanelExtender ID="CollapsePanel1" runat="server" SuppressPostBack="true" CollapseControlID="btnCancel" Collapsed="true" CollapsedText="Show Time" ExpandControlID="imgPostQuestion" ExpandedText="Hide Time" TargetControlID="panelPost"> cc1:CollapsiblePanelExtender>

Your TargetPanel is here

<asp:Panel ID="panelPost" runat="server" CssClass="cpBody">

<div>

//Ur collapsible Content

div>

asp:Panel>

And now we are preventing the flickering by the CSS style and the style is as follows.

.cpBody

{

height:0px;

overflow: hidden;

}

There we found the solution for the flickering..

Convert String To Title Case in C#

Here is the code to convert any string to Title Case in C#.

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

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.Xml.Linq;

using System.Data.SqlClient;

using System.Text;

using System.Net.Mail;

using System.Text.RegularExpressions;

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

{

protected void Page_Load(object sender, EventArgs e)

{

string strInsName;

strInsName = "hello world";

strInsName = strInsName.ToLower();

strInsName = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(strInsName);

Response.Write(strInsName);

}

}

First we need to convert the string to lower.. Only then the System.Globalization.CultureInfo.CurrentUICulture class will convert the string to Title Case.

Handling PostBack on Url Rewriting

So many of us stuck up with the problem of Postback during URL rewriting. During Postback the Url breaks up and throws error. Here is a solution to overcome this. We need to write this script in the last of the page (ie. In The Body Section.)

<script language="javascript">

function NotPostback(sNewFormAction)

{

if(document.layers) //The browser is Netscape 4

{

document.layers['Content'].document.forms[0].action = sNewFormAction;

}

else //It is some other browser that understands the DOM

{

document.forms[0].action = sNewFormAction;

}

}

NotPostback(document.URL);

script>

This calls the same Url on Postback too and thus it is solved..

Custom SEO Friendly Paging in Datalist like Google


Let’s see how to do paging with Datalist in as Next, Previous and with customized Page numbers as that of Gridview.

Here I have the following things..

i) A datalist dlCollegeList to which we are to implement the paging

ii) Two Hyperlinks (hyPrevious & hyNext) for navigating backward and forward

iii) Finally, a literal (litPaging) for displaying page numbers.

Here am using the stored procedure to fill my datalist and now let’s move to the implementation.

My datalist and Navigation links markup is as follows.

<div>

<asp:DataList ID="dlCollegeList"runat="server"

OnItemDataBound="dlCollegeList_ItemDataBound"onitemcommand="dlCollegeList_ItemCommand"Width="100%"

>

<ItemTemplate>

<div class="col-photo"><asp:HyperLinkID="hyInstLogo" runat="server"

NavigateUrl='' ><asp:ImageButton ID="imgLogo"ToolTip='' runat="server"Width="63px" Height="60px"CssClass="col-photo-border"/>asp:HyperLink>div>

<div class="col-cour-name">

<h4><asp:Label ID="lblclgId"runat="server" Text=''Visible="false">asp:Label><asp:HyperLink ID="hyinstName"runat="server"

NavigateUrl=''Text=''>asp:HyperLink>h4>

div>

<divclass="cityname"><asp:HyperLinkID="hyCity" runat="server"Text=''>asp:HyperLink><asp:LabelID="lblCity" runat="server" Text=''Visible="false">asp:Label>div>

div>

ItemTemplate>

asp:DataList>

<div id="pagination">

<ul>

<li> <asp:HyperLinkID="hyPrevious"runat="server">Previousasp:HyperLink>li><li><asp:Literal ID="litPaging"runat="server"EnableViewState="true">asp:Literal>li><li><asp:HyperLink ID="hyNext"runat="server">Nextasp:HyperLink>li>

ul>

div>

div>

Stored Procedure :

CREATE PROCEDURE[dbo].[listInstitute]

@startRowIndex int,

@pageSize int,

@totalCount int output,

@category varchar(max)

AS

BEGIN

SET NOCOUNT ON;

SET @totalCount = 0

SET @startRowIndex =@startRowIndex + 1

BEGIN

SELECT * FROM (

Select collegedetails.*,ROW_NUMBER() OVER (ORDER BYcollegedetails.inst_name asc) asRowNum

FROM collegedetails wherecategory like '%' + @category + '%'

) as ArticleList

WHERE

category like '%'+@category+'%'and (RowNum BETWEEN@startRowIndex AND(@startRowIndex + @pageSize) -1)

ORDER BY inst_name DESC

SELECT @totalCount =Count(clgid) FROM collegedetailswhere category like'%'+@category+'%'

END

END

This is the stored procedure which is used to fill the datalist and lets see the attributes used here.

· The startRowIndex is the one which sets the initial row to display and this calculates the rowindex of records to be displayed in that particular page.

· the pageSize denotes the number of records per page,

· totalCount gets the total number of records returned by the select command

Code Behind :

Declarations:

int _startIndex = 0;

int _thisPage = 1;

int _pageSize = 10;

int _totalNumberOfRows = 0;

string sPage;

SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

private void BindGridView ()

{

DataTable dTable = newDataTable();

using (SqlConnection conn = newSqlConnection(connStr))

{

using (SqlCommand dCmd = newSqlCommand())

{

SqlParameter[] prms = newSqlParameter[4];

prms[0] = newSqlParameter("@startRowIndex",SqlDbType.Int);

prms[0].Value = _startIndex;

prms[1] = newSqlParameter("@pageSize",SqlDbType.Int);

prms[1].Value = _pageSize;

prms[2] = newSqlParameter("@totalCount",SqlDbType.Int);

prms[2].Direction =ParameterDirection.Output;

prms[3] = newSqlParameter("@category",SqlDbType.VarChar);

prms[3].Value = Request["category"].Replace("-"," ");

dCmd.CommandText ="listInstitute";

dCmd.CommandType =CommandType.StoredProcedure;

dCmd.Parameters.AddRange(prms);

dCmd.Connection = conn;

using (SqlDataAdapter dAd = newSqlDataAdapter())

{

// assign the select command to the Adapter object

dAd.SelectCommand = dCmd;

// now open the connection

conn.Open();

dTable.Clear();

dAd.Fill(dTable);

conn.Close(); // close the connection

}

_totalNumberOfRows =int.Parse(prms[2].Value.ToString());

}

}

dlCollegeList.DataSource = dTable;

dlCollegeList.DataBind();

litPaging.Text = GetPaging(_totalNumberOfRows, _pageSize, 10);

//LitPagingTop.Text = GetPaging(_totalNumberOfRows, _pageSize, 10);

}

string GetPaging(int totalRecords,int pageSize, inttotalNumericLinks)

{

if (totalRecords <= pageSize)

{

return "";

}

StringBuilder str = newStringBuilder();

//Get Total no of pages

int totalPages = totalRecords / pageSize + (totalRecords % pageSize > 0 ? 1 : 0);

//Get Current Page no

int currentPageNo = 1;

string pageUrl = Context.Request.Url.AbsolutePath;

if(Context.Request.QueryString["page"] == null)

{

currentPageNo = 1;

}

if(Context.Request.QueryString["page"] != null)

{

currentPageNo = 1 + (Convert.ToInt32(Context.Request.QueryString["page"]) - 1);

}

//Add previous button

if (currentPageNo > 1)

{

str.Append(string.Format("href=\"http://www.yoursite.com/ListInstitute/"+Request["category"].ToString()+ "/{0}\" title=\"Previous page\">", (currentPageNo - 2) + 1));

}

//Add Numeric link

int sp, ep;

if (totalNumericLinks >= totalPages)

{

sp = 1;

ep = totalPages;

}

else

{

if (currentPageNo - totalNumericLinks / 2 > 0)

{

ep = (currentPageNo + totalNumericLinks / 2 - (totalNumericLinks - 1) % 2);

ep = ep <>

}

else

{

ep = totalNumericLinks;

}

sp = ep - totalNumericLinks + 1 > 0 ? ep - totalNumericLinks + 1 : 1;

}

for (int p = sp; p <= ep; p++)

{

//For Current Page, No Link, Bold Text

if (p == currentPageNo)

{

str.Append(String.Format(" {0}", p.ToString()));

}

else

{

str.Append(String.Format(" + Request["category"].ToString() +"/{1}\" title=\"{0}\">{0} ", p, (p - 1) + 1));

}

}

if (currentPageNo == totalPages)

{

hyNext.Visible = false;

// hyNextTop.Visible = false;

}

if (currentPageNo == 1)

{

hyPrevious.Visible = false;

//hyPreviousTop.Visible = false;

}

if (Request["page"] == null)

{

hyNext.Visible = true;

//hyNextTop.Visible = true;

}

if (currentPageNo > 1)

{

hyPrevious.Visible = true;

//hyPreviousTop.Visible = true;

}

return str.ToString();

}

GetPaging is the function which Is used to perform the paging as per our requirement. Here I have customised the GetPaging function to return only 10 pagenumbers. So the Literal control displays only 10 page numbers in between the Previousand Next links and this can be modified according to your requirement.




https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdxlvdumNPashziCCv79lPkU5NIlwXypVH9o8FLYZixZ4crWV87wSh9RHG1WCfP4vFr9dmmhoFEbB0bjTa5u1QseHOI50WKWcok6XCq3B1FAXjrNThyphenhyphenRBFouavmCpuV98drnmewa3X1j0/s320/page-middle.JPG


https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgg9iEZf3XrINwWjfOgKou5cUqmiZQ1bS0RN79UmI0UReGPkHVSWhD32HjZ7FVnX11Yrpr3-P8HSzeRmv6eOvQOKpwd6X4xg7BBTKLTAWq3tTncKT30EuHk99ONX71Bzu429Z296IDI2gg/s320/paging.JPG

You could see the page numbers between the links. This pagenumber will be passed through the query string for calculating the startindex and rowindex of the records to be displayed. Moreover this paging is SEO friendly.

BindGridView is the function which executes the stored procedure.

And now in my PageLoad my function is called as below..

protected void Page_Load(objectsender, EventArgs e)

{

if (!IsPostBack)

{

// check for current index

if (Request["page"] != null)

{

int.TryParse(Request["page"].ToString(), out _thisPage);

s =Convert.ToInt32(Request["page"].ToString());

st = (s - 1) * 10;

string str = Convert.ToString(st);

int.TryParse(str, out _startIndex);

}

int pSer = s - 1;

int nSer = s + 1;

if (s == 0)

{

nSer = 2;

}

BindGridViewArticels(); // bind articles

hyPrevious.NavigateUrl ="http://www.yoursite.com/ListInstitute/"+Request["category"].ToString()+"/" + pSer;

hyNext.NavigateUrl ="http://www.yoursite.com/ListInstitute/"+ Request["category"].ToString() +"/" + nSer;

}

if (_totalNumberOfRows <= 10)

{

hyNext.Visible = false;

hyPrevious.Visible = false;

}

}

And now with this Custom pagination for Datalist is done. So here is my Datalist with paging implemented.





https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUUxUGLpumLC1YJSZOpY-1fQWPAmrS3urBF2z9zIoEwemggD00JfLz6BPcVWtcET7Mu0_Wd5ehsE_ByTaDgOvNLlp5VaJHK_V1xIwnr9YQJe5R_CoO5diuKbJqGKK7EUAbiPGh5rjW9K4/s320/fullpage.JPG

You can see my Datalist with Pagination implemented