Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for November, 2008

Set Focus on dropdown list after Partial Postback

Posted by Ramani Sandeep on November 28, 2008

——————————————————————-
Problem
——————————————————————-
I have a dropdownlilst that does a Partial postback when it’s index is changed.

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>

<ContentTemplate>

<asp:DropDownList ID=”ddlCountry” runat=”server” CssClass=”combobox” AutoPostBack=”true”

OnSelectedIndexChanged=”ddlCountry_SelectedIndexChanged” onblur=”check_ddlCountry()”

TabIndex=”5″>

</asp:DropDownList>

<asp:DropDownList ID=”ddlState” runat=”server” CssClass=”combobox” AutoPostBack=”true”

OnSelectedIndexChanged=”ddlState_SelectedIndexChanged” onblur=”check_ddlState()”

TabIndex=”6″>

</asp:DropDownList>

</ContentTemplate>

</asp:UpdatePanel>

After it does the Partial postback, it loses focus and when I click tab, I start from the item that

is TabIndex=”1″. I would like to set focus back to this item.

———————————————-
Solution 1
———————————————-

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int CountryID = Convert.ToInt32(ddlCountry.SelectedValue);

if (CountryID > 0)
{
FillState(CountryID);
}

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), “FocusOnState”,

“document.getElementById(‘” + ddlState.ClientID + “‘).focus(); “, true);

}

———————————————-
Solution 2
———————————————-
If Your page is AJAX enabled page and you have ScriptManager on the page, then you can use this code.

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
int CountryID = Convert.ToInt32(ddlCountry.SelectedValue);

if (CountryID > 0)
{
FillState(CountryID);
}

ScriptManager manager = ScriptManager.GetCurrent(this);
manager.SetFocus(“ddlState”);

}

Both Solution Work for me. Hope this help you also..

Thanks, Enjoy Programming.

About these ads

Posted in ASP.NET Ajax | Tagged: , , | 4 Comments »

Filtering & sorting DataTables with DataTable.Select()

Posted by Ramani Sandeep on November 26, 2008

We all know that connections to databases from within our applications cost us processor cycles and thus time so it’s a good idea to only ‘talk’ to your database when you really need too. In the .NET framework items like DataSets and DataTables etc. facilitate this to a large degree. In this post let’s take the .Select() method of the DataTable class as evidence of this.

.NET framework 2.0 DataTable.Select() method

The DataTable.Select() method has four overloads and allows you to filter and display your rows in a number of ways in a manner similar to the way SQL does. The method can accept an expression string which lthough not nearly as powerful as full blown SQL does provide the advantage of not having to go back to the database to do simple things like showing records relevant to only a certain date range or a certain customer, product etc.

Below is some of the valid expressions and filters you can pop into the Select() method to narrow your record set.

Standard Operator based expressions

Things like >, <, >=, <=, =, <> are all supported of course. If your DataTable was called salesStaff and you only wanted to return staff with sales of greater than 100, you could do this with salesStaff.Select(”sales > 100″). An array of DataRows will be returned, so depending on what you want to do with the results of the Select() method you may have to copy them back into another DataTable… more on that below.

More SQL query like expressions

Filtering by Like is also supported by the Select() method which I think is quite sweet. Wildcards as in SQL are * and %. Just like most variations of SQL support aggregate types so too does the Select() expression ‘language’. Items like AVG, MIN, MAX, SUM and COUNT are all supported, so too are functions like LEN and SUBSTRING. If you need to test multple columns/conditions you can join them with the AND or OR operators but be careful if your using .Net 1.1 SP 1 as there was a documented bug in .Select() when it was used with AND.

Sorting with DataTable.Select()

This is probabely the main way I use the Select() method. Its supported not via the expression parameter but via the sort parameter which is available in two overloaded .Select() methods. Its format is columnName asc/desc.

Importing DataTable.Select() method results into another DataTable

Putting the results from a Select() query into another DataTable is often a requirement say for instance if you wanted to bind your results to a control. As mentioned above the Select() method returns an array of DataRows and since DataRows are the main building blocks of DataTables the process is very easy.

//copy the schema of source table
DataTable above24 = dt.Clone();

//get only the rows you want
DataRow[] results = dt.Select(”age > 24″);

//populate new destination table
foreach (DataRow dr in results)
above24.ImportRow(dr);

DataTable.Select() shortcomings

The main things I don’t like about the .Select() method is how you have to go through intermediary steps to get your results into another DataTable, why can’t it just return another DataTable (which is directly bindable to a load of .NET data controls) and its lack of support for selecting distinct/unique rows which is often needed. As as note on that last one, it is possible to return distinct rows in a DataTable using LINQ which is a .NET 3.5 component, however that topic might best be served with another post at a later date.

Can’t I just use a DataView instead of calling DataTable.Select()?

You can and DataViews are directly bindable to many controls too, however it is not always the best solution due to the generally accepted believe among many developers that .Select() is much faster than using the DataView equivalent of RowFilter (property). I regularly interchange between the two for a lot of small database projects, however for the projects where I need to be processing a mega amount of data I pretty much stick with .Select() 100% of the time as I reckon it provides real speed (as in seconds, not PC invisible micro time) advantages compared to DataViews.

Posted in ADO.NET | Tagged: , , | 2 Comments »

File Upload Control is not working in Update Panel

Posted by Ramani Sandeep on November 22, 2008

The essence of the problem is that the FileUpload control does not work with asynchronous postbacks, and therefore does not work from within an AJAX UpdatePanel.

The technique presented in this article allows the FileUpload control to work within an UpdatePanel, by forcing a full postback; however, the rest of the controls can still take advantage of the asynchronous postbacks provided by the UpdatePanel.

Solution
————

The trick is to force the file upload control to perform a full postback, and we do this using triggers. Triggers allow the developer to specify what will cause partial and full postbacks. They must be defined within the UpdatePanel but outside of the ContentTemplate. We want to create a trigger that will instruct the button that we are using for the upload to perform a full postback.

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”conditional”>
<Triggers>
<asp:PostBackTrigger ControlID=”Button1″ />
</Triggers>
<ContentTemplate>

<asp:FileUpload ID=”FileUpload1″ runat=”server” />
<asp:Button ID=”Button1″ runat=”server” Text=”Upload” OnClick=”Button1_Click” />

</ContentTemplate>
</asp:UpdatePanel>

Posted in ASP.NET, ASP.NET Ajax | Tagged: , , | 8 Comments »

AJAX – TextBoxWatermark

Posted by Ramani Sandeep on November 21, 2008

TextBoxWatermark is an ASP.NET AJAX extender that can be attached to an ASP.NET TextBox control to get “watermark” behavior. When a watermarked TextBox is empty, it displays a message to the user with a custom CSS style. Once the user has typed some text into the TextBox, the watermarked appearance goes away. The typical purpose of a watermark is to provide more information to the user about the TextBox itself without cluttering up the rest of the page.

TextBoxWatermark Properties

<ajaxToolkit:TextBoxWatermarkExtender ID=”TBWE2″ runat=”server”
TargetControlID=”TextBox1″
WatermarkText=”Type First Name Here”
WatermarkCssClass=”watermarked” />

  • TargetControlID – The ID of the TextBox to operate on
  • WatermarkText – The text to show when the control has no value
  • WatermarkCssClass – The CSS class to apply to the TextBox when it has no value (e.g. the watermark text is shown).

Posted in ASP.NET Ajax | Tagged: | Leave a Comment »

Passing Values from One Page to Another Page – ASP.NET

Posted by Ramani Sandeep on November 21, 2008

Passing parameters from one page to another is a very common task in Web development. Granted, its importance and frequency has faded a bit with ASP.NET’s inherent preference for postback forms, but
regardless, there are still many situations in which you need to pass data from one Web page to another.

There are three widely used methods of passing values from one page to another in ASP.NET
Main

1. Using Query String

We usually pass value through query string of the page and then this value is pulled from Request object in another page.

FirstForm.aspx.cs
—————–
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);

SecondForm.aspx.cs
——————
TextBox1.Text = Request. QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:

FirstForm.aspx.cs
—————
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));

SecondForm.aspx.cs
—————–
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

2. Passing value through context object

Passing value through context object is another widely used method.

FirstForm.aspx.cs
—————
TextBox1.Text = this.Context.Items["Parameter"].ToString();

SecondForm.aspx.cs
——————
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:

FirstForm.aspx.cs
—————
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}

And we create a javascript function to post the form.

SecondForm.aspx.cs
—————–

function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.

FirstForm.aspx.cs
————–
<asp:Button id=buttonPassValue style=”Z-INDEX: 102″ runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>

SecondForm.aspx.cs
—————–
TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.

SecondForm.aspx
—————
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1″);
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.
Conclusion Passing values between pages is another common task accomplishes in web based development. As we have discussed many of mechanisms above, I prefer and recommend to use Query String then other
methods for its clean and simple implementation as long as your parameter doesnt have security concern.

Reference :

http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

Posted in ASP.NET | Tagged: , , , | 40 Comments »

How To Change Row Color of Gridview on Mouse Over Event

Posted by Ramani Sandeep on November 19, 2008

For my example, I’m using alternating background colors on rows (which you should do too, it makes things so much more readable). This causes me to add a couple extra lines so that I make sure I’m setting my rows back to the correct color on MouseOut.

Here is the code for that :

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Alternate)
{
e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’#FFFFE1′;”);
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’#f7fff8′;”);
}
else
{
e.Row.Attributes.Add(“onmouseover”, “this.style.backgroundColor=’#FFFFE1′;”);
e.Row.Attributes.Add(“onmouseout”, “this.style.backgroundColor=’#eefef0′;”);
}
}

}

Posted in ASP.NET | Tagged: , , | 1 Comment »

Selecting Rows Randomly from a table

Posted by Ramani Sandeep on November 18, 2008

If you use Microsoft SQL Server 2000, you likely have run into the following problem: You want to select a random sampling of rows from a large table with lots of rows, but you are unsure of how to do so. Having a random sampling of rows can be useful when you want to make a smaller version of the table or if you want to troubleshoot a problem by seeing what kinds of rows are in the table.

To get a random sampling, you might be tempted to select the top n rows from the table. However, this sample is not random, and the first n rows are not necessarily representative of the whole table. Other solutions exist that involve adding columns to the tables; however, adding columns is not always possible or practical.

The standard way to grab random rows from a small table is to use a query such as the following:

SELECT TOP 10 Stud_ID , Stud_Name , Student_Marks_Total
FROM StudentDetails
ORDER BY NEWID()

The key here is the NEWID function, which generates a globally unique identifier (GUID) in memory for each row. By definition, the GUID is unique and fairly random; so, when you sort by that GUID with the ORDER BY clause, you get a random ordering of the rows in the table. Taking the top 10 percent (or whatever percentage you want) will give you a random sampling of the rows in the table.

Often, when questions about how to select random rows are asked in discussion groups, the NEWID query is proposed; it is simple and works very well for small tables. However, the NEWID query has a big drawback when you use it for large tables. The ORDER BY clause causes all of the rows in the table to be copied into the tempdb database, where they are sorted. This causes two problems:

–>The sorting operation usually has a high cost associated with it. Sorting can use a lot of disk I/O and can run for a long time.

–>In the worst-case scenario, tempdb can run out of space. In the best-case scenario, tempdb can take up a large amount of disk space that never will be reclaimed without a manual shrink command.

Posted in SQL Server | Tagged: , , | Leave a Comment »

Fill Year in DDL

Posted by Ramani Sandeep on November 16, 2008

here is the code to fill year dropdownlist :

int intYear = System.DateTime.Now.Year;

for (int i = 78; i >= 0; i–)
{
string strYear = Convert.ToString(intYear – i);

ddlYear.Items.Add(new ListItem(strYear, strYear));
}
ddlYear.Items.Insert(0, new ListItem(“Year”, “-1″));

this is simple ..but very usefull code..

Posted in ASP.NET, C# 2.0 | Tagged: , | Leave a Comment »

Using FilteredTextBoxExtender

Posted by Ramani Sandeep on November 16, 2008

FilteredTextBox is an extender which prevents a user from entering invalid characters into a
text box. Note that since this effect can be avoided by deactivating JavaScript, you should
use this extender as a convenience for your users, but you must never expect that the data
being sent to the server consists of “valid” chars only.

Only math symbols (+,-,*,/,=,.) and numbers:

<ajaxToolkit:FilteredTextBoxExtender ID=”ftbe” runat=”server”
TargetControlID=”TextBox3″
FilterType=”Custom, Numbers”
ValidChars=”+-=/*().” />

  •   TargetControlID – The ID of the text box for this extender to operate on
  • FilterType – A the type of filter to apply, as a comma-separated combination of Numbers,

LowercaseLetters, UppercaseLetters, and Custom. If Custom is specified, the ValidChars
field will be used in addition to other settings such as Numbers.

  • FilterMode – A the filter mode to apply, either ValidChars (default) or InvalidChars. If set to

InvalidChars,FilterType must be set to Custom; if set to ValidChars, FilterType must contain Custom.

  • ValidChars – A string consisting of all characters considered valid for the text field, if “Custom” is

specified as the filter type. Otherwise this parameter is ignored.

  • InvalidChars – A string consisting of all characters considered invalid for the text field, if “Custom” is

specified as the filter type and “InvalidChars” as the filter mode. Otherwise this parameter is ignored.

  • FilterInterval – An integer containing the interval (in milliseconds) in which the field’s contents are filtered,

defaults to 250.

Posted in ASP.NET Ajax | Tagged: | Leave a Comment »

How to limit the amount of decimals to 1 in textbox?

Posted by Ramani Sandeep on November 16, 2008

use the following code :

Answer
=========

<asp:TextBox ID=”TextBox1″ runat=”server” />
<cc1:MaskedEditExtender
ID=”MaskedEditExtender1″
runat=”server”
TargetControlID=”TextBox1″
Mask=”9{9}.99″
MaskType=”Number”
InputDirection=”RightToLeft” />

Posted in ASP.NET, ASP.NET Ajax | Tagged: , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.

Join 124 other followers