Friday, May 29, 2009

Check uncheck all rows of gridview (select or deselect all rows at once)

The asp.net gridview data control offers lots of features, that we all know. Adding some cool effects may make this control more usable. For instance, we could check or uncheck all the checkboxes in a column of the gridview control. A column [leftmost column usually] consisting of checkbox control is generally used to select a row. Sometimes we may need to check (and uncheck) all the rows of the gridview. Purpose of doing so may be different depending upon the business requirement. And if we need to do so, we can!


Fig. Check Uncheck all rows in a gridview


Let's be quick to implement check/uncheck all the rows of gridview at once in asp.net gridview. Let's have the markup for the gridview first.

<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">

<HeaderTemplate >

<input id="chkAll" onclick="javascript:SelectDeselectAllCheckboxes(this);"

runat="server" type="checkbox" />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="100" />

<asp:BoundField HeaderText="Address" DataField="Address" />

</Columns>

</asp:GridView>

Watched the checkbox control in the header template of the first column? We will use this checkbox to select or deselect all the rows in the gridview. Also mark that clicking this checkbox will call the javascript function SelectDeselectAllCheckboxes. Now is the time to define some javascript snippets to get help from.

<script type="text/javascript">  

function SelectDeselectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox



var oItem = spanChk.children;

var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0];

xState=theBox.checked;

elm=theBox.form.elements;

for(i=0;i<elm.length;i++)

if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)

{

//elm[i].click();

if(elm[i].checked!=xState)

elm[i].click();

//elm[i].checked=xState;

}

}

</script>

The task done by the javascript function is simple. It takes the checkbox itself as the input. If it is checked, it searches for all the checkboxes in the gridview and checks them. And reversely, if it is unchecked, all those checkboxes will be consequently unchecked.

There is no need of any codebehind just for this functionality. So I am leaving other parts including databinding code. In fact, for most of the test purposes I do Create DataTable Programmatically and bind the gridview, formview or detailsview to that DataTable.

The only drawback with this technique is that it treats all the checkboxes in or outside the gridview control equal.

You can post your comment, rate this post or add this post to your favourites or share it. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Wednesday, May 27, 2009

Fill asp.net formview textbox to initial value in insert mode

In most scenarios, the asp.net data controls like detailsview and formview have empty controls in insert mode. This means any field that requires [or at least expects] user input will not contain any data. But this default configuration sometimes needs to be modified. Say, we would like to fill the date field in a textbox to current date, so that it will be easier for user. This is just an example. This can be the asp.net dropdownlist from where we would like to select one value initially, or it may be other asp.net user input control like checkbox or radiobutton. In such scenario, we can set the control value to some default initial value. With datacontrols like formview and detailsview, it takes a little effort [simple and tricky!]. In this short post [In fact I am expecting to keep this post as such as possible since there is no need of much explanation: concept is crystal clear and implementation is also easy!] I am going to show the simple coding practice to initiate the formview or detailsview control to some value. I will be choosing formview to show the example.


Fig: Setting a textbox to an initial value in insert mode of an asp.net formview control

The formview can have one of three modes at one instance of time. They are Insert, Edit and ReadOnly modes. We should be careful about the current mode of the formview before we do reference any control. This is because a textbox in edit template may not be available in the read only mode, for instance. So we will check the current mode of the formview and search for the textbox with its ID. Then we can easily set the value of the control. Let's have a formview first.

FormsView Design Markup

<asp:FormView ID="FormView1" runat="server" HeaderText="Fill the Credentials below." DefaultMode="Insert">

<ItemTemplate>

<table>

<tr>

<td>

Name: <asp:Label ID="lblName" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td>

Date of Test: <asp:Label ID="lblTestDate" runat="server"></asp:Label>

</td>

</tr>

</table>

</ItemTemplate>

<InsertItemTemplate>

<table>

<tr>

<td>

Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td>

Date of Test: <asp:TextBox ID="txtTestDate" runat="server"></asp:TextBox>

</td>

</tr>

</table>

</InsertItemTemplate>

</asp:FormView>

We simply have two fields in the formview: name and date of test. Our intension will be to initiate the value of the date of test field to current date.

CodeBehind for the example

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Call to filling textbox in the insert mode;
//I assume here that initially the formview
//is in insert mode
FillDefaultVaueInFormView();
}
}

public void FillDefaultVaueInFormView()
{
//if the formview is in insert mode
if (FormView1.CurrentMode == FormViewMode.Insert)
{
//txtTestDate is the id of the 'date of text' textbox in formview
TextBox txtTest = FormView1.FindControl("txtTestDate") as TextBox;
if (txtTest != null)
{
txtTest.Text = DateTime.Now.ToShortDateString();
}
}
}

Now the formview will have the date of test field initiated to the current date. Let me repeat- Simple and Tricky! You can post your comments and suggestions from the form below. You can rate this post as well. You can even share this post. Just add this post to the social sites! Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Friday, May 22, 2009

Click the button on keypress in asp.net TextBox

In this post, I am explaining the button click functionality on key press in a textbox. I am using javascript to link the input textbox and the associated button that has to be clicked when the enter key is pressed in the textbox. One can preview it by taking the example of search textbox and GO button!


Fig. Clicking asp.net button on enter key press in textbox

We have seen search textboxes in almost all of the websites which imply 'Go' or 'Search' button click when Return key (Enter key) is pressed. Naturally, users love to press enter key instead of clicking search button next to the input textbox. Wouldn't it be nice if we could do the same for our web pages also? Yeah, I have implemented the button click feature on keypress in textbox control many times. But the last time practice on a web application that added both the textbox and the search button dynamically via javascript was really interesting story that inspired me to re-share the code [since I also learnt it on Internet].

Design Page Markup (SearchPage.aspx)
We do have one textbox and one button in the search page.

<div>

Search Text: <asp:TextBox ID="txtSearchBox" runat="server"></asp:TextBox>

<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />

</div>

JavaScript Code    
This javascript code will be invoked when enter key is pressed in the textbox.

<script>

function clickButton(e, buttonid){

var evt = e ? e : window.event;

var bt = document.getElementById(buttonid);

if (bt){

if (evt.keyCode == 13){

bt.click();

return false;

}

}

}

</script>

We put this javascript code snippet within the head section of the design page.

Code Behind (SearchPage.aspx.cs)

//page load event handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//add attribute on the search textbox
//so that when enter key is pressed in the textbox,
//the search button will be fired
txtSearchBox.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')");
}
}

//when search button is clicked
protected void btnSearch_Click(object sender, EventArgs e)
{
//my function to perform search
}


Here we add the onkeypress attribute to the textbox. When a key is pressed, the keycode will be passed to the javascript function. The javascript function checks if this is the enter key, and it is enter key then the button click is invoked by the javascript code.

So far we implemented button click on enter key press from an asp.net web control. To add a little user interactivity in the search textbox, you can implement google search like watermark effect in the search textbox. If you further want to prevent multiple postback, you can just disable asp.net button after first click and enable after postback completes.

Don't forget to expose your views via comment box beneath this post. You can freely share this post! Happy Programming!

Shout it kick it on DotNetKicks.com 

Monday, May 18, 2009

Contact Me

Thank you!

Dear reader,

Thank you for taking time to drop your feedback/suggestion/query. An email has been sent to you to confirm your action. I will be listening you very soon!

You can now go to dotNETspidor home page and enjoy your day!

Thank you very much. Have nice dotNETspidor surfing!

About Me



My name is Sangam Uprety, a computer engineer from Nepal. For 2 years I have been programming asp.net web applications. I do love playing with javascript and ajax for client side programming. I do program SQL Server and Oracle databases. I also code DotNetNuke (DNN) modules for portal development. In fact developing multi-featured portals is my passion!


Besides programming, I love reading books. Songs? Obviously, all kinds! I don't find myself anywhere if there are no social activities in my life. I believe social works have always saved nations.


I love watching football games. Ok..ok..did I mention I do write also? If I didn't, no problem. I love writing. Thanks goes to Karl Marx who said that people who write diaries never fail! And I do run a blog. Yeah, dotNETspidor: A dot net programming blog !


Would like to contact me or just drop me some words? Ok, you are heartily welcome to Leave Your Valuable Message/Feedback/Suggestions right from this blog!


Thank you for being interested about me!

List all files in a folder in an asp.net gridview

We do have a folder (and a number of sub folders) with a number of various files in those folders (and sub folders). Now we do need to list all those files in an asp.net gridview control [for the purpose of organizing those files, or for the preview of files uploaded till now, say]. We can do it in asp.net using the System.IO namespace. In this article, I am going to show the coding for displaying all files in a folder in an asp.net gridview. In fact, as a bonus, we will do the listing of all files in a root folder and all its subfolders also.

Fig: Snapshot of displaying all files in a folder and its subfolders in an asp.net gridview control

Design Page Markup (ListFiles.aspx)
We first need to have a web page with the gridview control in it.

<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
</form>

Remember, we have set the AutoGenerateColumns field to true. So all the fields that is present in our source will be displayed by the gridview, each as a separate column. (I have removed the formatting of the gridview markup to make the code clear. Please your own formatting for the gridview.)

Code behind page (ListFiles.aspx.cs)
Now here goes the actual code to bind all the files in the folder "Resources", that resides at the root of the web site, and all its subfolders.

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

public void GetFilesAndFolders()
{
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Resources"));
FileInfo[] fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
GridView1.DataSource = fileInfo;
GridView1.DataBind();
}

We have used the DirectoryInfo and FileInfo classes of the System.IO namespaces. The DirectoryInfo class will get the root directory of the provided folder name. And we have used the DirectoryInfo class's GetFiles method. This method has two overloads. We can specify the file patterns (e.g. "*.txt" for text files only, or "*.*" for all types of files etc) and the search option- if to list all the files in all the subdirectories of the root directory (in our case, "Resources" folder) provided as the input, or just to list the files in the root directory.

When we browse the page, we see the gridview populated with 13 fields, which I hope need no explanation. However for your reference I have listed the fields here: LastAccessTimeUtc, Length, LastWriteTime, LastWriteTimeUtc, FullName, IsReadOnly, CreationTimeUtc, LastAccessTime, CreationTime, Name, Exists, Extention, and DirectoryName. For the description of each field, please visit FileInfo class Properties, msdn document.

Now from those thirteen fields, we can choose and display the required ones. Please don't forget to share your views, suggestions or comments as always. Thank you. Happy programming!

kick it on DotNetKicks.com pimp it Shout it

Popular Posts

Recent Articles