| 0 comments ]

Sometime ago I saw an interesting question in asp.net forum. It raised my enthusiasm. I started to code the requirement. And I found one. Here goes the requirement:

Hi!

I have two text boxes inside my aspx page: a) the "txt1" and b) the "txt2". Both text boxes have CalendarExtender controls attached:
a) the txt1 has the "CalendarExtender1"
b) the txt2 has the"CalendarExtender2".

All I want is this:
Using client-side script (or other method without postbacks), I want when the user chooses a date from CalendarExtender1, the same date plus a day front to go to the txt2.

For example:
If the user chooses 03/28/2009 in the CalendarExtender1, I want the value of the txt2 to be the 03/29/2009....
Also, if the month reaches the end, I want the txt2 to take the new moth.

For example:
If the user chooses 03/31/2009 in the CalendarExtender1, I want the value of the txt2 to be the 04/01/2009....

That behavior I want to exists only to the CalendarExtender1 like I describe it. I don't want the user to be able to do this with CalendarExtender2 (the CalendarExtender2 has the default behavior)...

How can I accomplish that? Thank you very much!

There are two solutions provided to this requirement. Let me put them here.

Solution1: (By Kinjalin)

Here you have to add it in Javascript.

<cc1:CalendarExtender ID="ClExFromDt"                     runat="server"                     TargetControlID="TxtFromDate"                     PopupButtonID="BtnFromCal"                     Format="dd/MM/yyyy"                     OnClientDateSelectionChanged="AddDate"                     CssClass="calExt_Theme1"></cc1:CalendarExtender>

Here on OnBlur, write a Javascript function addDate

on Page_Load write the line " Text1.Attributes.Add("onblur", "javascript:addDate();")

& in Javascript Fetch the Value using document.getElementByID("TextBox1").value

add it using below Javascript & bit of ur Logic

//create the date
var myDate = new Date();


//add a day to the date
myDate.setDate(myDate.getDate() + 1);


//add a week
myDate.setDate(myDate.getDate() + 7);

After adding Show it in your TextBox2

$get(TextBox2).value = myDate

Thats it.

Solution2: (By sangam100)

Hi MinimalTech ,

Here goes the prototype, which is close to what kinjalin posted:

Add this script in the design page:

<script>

function addDays() {

dateParts = document.getElementById('txtDate1').value.split('/');

year = dateParts[2];

month = parseInt(dateParts[0])-1;

day = parseInt(dateParts[1]) + 1;



newDate = new Date ( year, month, day );

year = newDate.getYear();

month = newDate.getMonth()+1;

day = newDate.getDate();

formattedDate = month + '/' + day + '/' + year;



document.getElementById('txtDate2').value=formattedDate;

}

</script>

Now in the design page:

Date1:<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>  Date2 (One day forward):<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox><cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate1" PopupButtonID="txtDate1"></cc1:CalendarExtender>

In the code behind.

txtDate1.Attributes.Add("onchange", "addDays();");

Now this works.

Hope this will be useful to all. Happy Programming!

| 0 comments ]

Many times we need to convert datetime to different strings representing date, varying from 2009/06/2009 to June 26, 2009, and so on. Microsoft sql server 2005 can do the job for us! I had the same need some time ago, and sql server did this for me. (By the way, don't we programmers often find it irritating to have datetime representations different in different data base providers and different programming languages? Yes. Exactly here is what I am pointing towards what sql server 2005 can do for us. Follow the rest of this article for the magic!)

This is the syntax:

CONVERT (data-type, date-time-string-input, date-display-style)

Parameters:
data-type: Any data type from nchar, nvarchar, char, varchar, binary, varbinary [length is optional, e.g. varchar(20) or varchar(22)
date-time-string-input: Date time string supplied as input (You can use GETDATE() function etc.)
date-display-style: The string style (You need '2009.06.26' or 'June 26, 2009' etc. You can even use the useful style number. Read on.)

Note: If you provide insufficient length, you may be trimming your result!

Now, here is a list of the sql query and the result to the query that will introduce a number of the ways to get desired date strings.

SELECT CONVERT(VARCHAR(20),GETDATE(),100) 
Result: Jun 26 2009 5:53PM

SELECT CONVERT(VARCHAR(20),GETDATE(),101)
Result: 06/26/2009

SELECT CONVERT(VARCHAR(20),GETDATE(),102)
Result: 2009.06.26

SELECT CONVERT(VARCHAR(20),GETDATE(),103)
Result: 26/06/2009

SELECT CONVERT(VARCHAR(20),GETDATE(),104)
Result: 26.06.2009

SELECT CONVERT(VARCHAR(20),GETDATE(),105)
Result: 26-06-2009

SELECT CONVERT(VARCHAR(20),GETDATE(),106)
Result: 26 Jun 2009

SELECT CONVERT(VARCHAR(20),GETDATE(),107)
Result: Jun 26, 2009

SELECT CONVERT(VARCHAR(20),GETDATE(),108)
Result: 17:49:42

SELECT CONVERT(VARCHAR(20),GETDATE(),109)
Result: Jun 26 2009 5:50:02

SELECT CONVERT(VARCHAR(20),GETDATE(),110)
Result: 06-26-2009

SELECT CONVERT(VARCHAR(20),GETDATE(),111)
Result: 2009/06/26

SELECT CONVERT(VARCHAR(20),GETDATE(),113)
Result: 26 Jun 2009 17:51:24

SELECT CONVERT(VARCHAR(20),GETDATE(),114)
Result: 17:51:44:397

SELECT CONVERT(VARCHAR(20),GETDATE(),120)
Result: 2009-06-26 18:00:17

SELECT CONVERT(VARCHAR(20),GETDATE(),121)
Result: 2009-06-26 18:01:14

SELECT CONVERT(VARCHAR(20),GETDATE(),126)
Result: 2009-06-26T18:02:00

As you can see, I have used the select statement to retrieve the desired sql query result. You can use it with any combination of sql query to perform any of the CRUD (Create, Read, Update and Delete) operations.

You can comment to add to the above list. It may be incomplete. Remember your participation is very important to make it more complete and more useful. You are as always heartily welcome to post you suggestions, comments, rate this article or spread the words by adding it to the social bookmarks! Happy Programming!


Shout it pimp it

| 2 comments ]

Programmers heavily use the asp.net gridview control. Adding some effects to the gridview will change the appearance so that user interactivity increases. One of such effects is highlighting the gridview row on mouseover. With this short background let's go for the design markup of the example gridview.

<asp:GridView ID="gridTest" runat="server" OnRowDataBound="gridTest_RowDataBound" AutoGenerateColumns="false">

<Columns>

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

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

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

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

</Columns>

</asp:GridView>

Now we have the asp.net gridview, why not choose the highlighted row's color? Let's define a style sheet class for highlighted row.

<style type="text/css">

/*for gridview row hover, select etc*/

.normalrow

{

background-color:white;

}

.highlightrow

{

background-color:#cccccc;

}

</style>

(The gridview markup shown above is only for example purpose. So you will not see any matches between the figure showing highlighted row and the example markup. Further you will also need to implement your own css styling, if you prefer any). Note the OnRowDataBound event handler in the gridview design markup. We will write some lines of code in this event handler to add the effect of highlighting gridview rows on mouse over. Here goes the code.

//row created event
protected void gridTest_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='highlightrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");
}
}

We have specified the css class to adapt by the gridview row on mouse over. At the same time, we need to assign another css class on mouse out so that the gridview will be highlighted only on mouseover and on mouse out the effect will be void. Happy programming!

kick it on DotNetKicks.com pimp it Shout it

| 9 comments ]

Efficient programmers use short keys in IDE like Visual Studio. This saves time and in many cases makes the work run faster also. I also love short keys. They are smart! And there also go some tricks that help make your visual studio days a party! I have listed here some short cuts and some tips with the hope that this will be helpful to you all.

Visual Studio Short-cuts

  1. Ctrl+F5 to run the website without debugging. F5 only will run the website in debugging mode.
  2. Stop Debugging: Shift+F5
  3. Restart Debugging: Ctrl+Shift+F5
  4. Break All: Ctrl+Alt+Break
  5. F11 to debug line by line downwards from the toggle point. This works with F10 also. In fact you can see F10 assigned for this task. See Debug menu in the visual studio.
  6. F9 to toggle a break point.
  7. To delete all the break points at once: Ctrl+Shift+F9. If you only wish to disable the break points you can go down the Debug menu.
  8. Ctrl+S to save the current document. Ctrl+Shift+S to save all the documents at once.
  9. Print a document directly from the visual studio? Press Ctrl+P. This will bring the print dialog.
  10. Ctrl+F to find a text. A find dialog will be displayed. Then you are left with a number of options.
  11. Ctrl+H or Ctrl+Shift+H for find and replace.
  12. Ctrl+G to go to the specific line number in the current document.
  13. Open the web browser right from within the visual studio? Press Ctrl+Alt+R.
  14. Irritated switching back and forth the design view and code behind page of a file? Use F7 to navigate back and forth the files of a page.
  15. Press F4 to view the properties window for a control from the design page.
  16. To view the server explorer: Ctrl+Alt+S
  17. To view the solution explorer: Ctrl+Alt+L
  18. To view the output window: Ctrl+Alt+O
  19. To view the toolbox: Ctrl+Alt+X
  20. Press Shift+Alt+Enter to view/undo full screen.
  21. Press Ctrl+O to open a document from the project folder.
  22. Ctrl+F11 to view disassembly: the machine level code!

Visual Studio Tips

  1. To view the start page, navigate View->Other Windows->Start Page
  2. To initiate the start page to display feed from a website, Tools->Options->Startup. Choose show start page at start from the combo fox. Input the start page news channel rss feed. Click Ok.
  3. To display line numbers in the documents, Tools->Options->Text Editor. Now click the editor you need to display number in. Check Line Numbers at the right side of the window.
  4. Initiate the home page for the web browser [opened by pressing Ctrl+Alt+R]? Follow Tools->Options->Environment->Web Brower. Set the home page and optionally the search page from the right side of the window.
  5. Know the class name or method name but confused the right namespace? Right click the class name or method name and click Resolve; you will see the reference you need to add. Click the reference. It will be added for the page.
  6. Using find window and clicking Find button each time to go to next match? Leave the trend. Just press F3 to go to next match!!

Shortcuts are the small but useful ladders of programming. You can use them to go up and down, left and right or south and north. I would like to heartily welcome to share your tips and tricks that you have learned from your dedicated play around with the visual studio. All the tips and shortcuts I have listed above are tested and learned from visual studio 2005. They may or may not work in visual studio 2008 and later versions. You can specify the compatibility of your trick that you are posting as comment in this article. Thank you very much. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

| 0 comments ]

How can I read the email address, smtp host, port number from my mail settings section of the web.config file in an asp.net web application? Yeah, we can specify an email address in the mail settings section of web.config file and read it from asp.net web page in the time of sending an email. We can also read the smtp host and port number which is necessary while sending email from an asp.net web page. I have already discussed: How to send email from asp.net web page. So here I would just put the coding to read email address, host, port number from mail settings section of web.config file in asp.net web application.

Let's look into the mail setting portion of a web.config file.

<system.net>

<mailSettings>

<smtp from=support@test.com>

<network host="mymailhostaddress" port="25"/>

</smtp>

</mailSettings>

</system.net>

While sending an email, we need from, to email addresses and an smtp client also. So the code snippet below puts them together.

using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

//the method to send email
public void SendMail()
{
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
SmtpSection smtpSection = mailSettings.Smtp;
//read the from email of the web.config file
string fromEmail = smtpSection.From;
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;

//..other code follows from here
//that sends the email

//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(fromEmail), new MailAddress("anup@best.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient(host, port);
try
{
client.Send(message);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
}
}

Using the code above, we easily accessed the important information from mail settings section of the web.config file. Please note again that I have just put the coding of reading information form web.config file. You can learn from here to Send Email in asp.net web page so that you can combine what this article provides with sending email in asp.net web application. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

| 0 comments ]

Most of the times asp.net programmers need to extract data out of the asp.net datacontrols like formview, detailsview or gridview. Mostly we use FindControl method of the data control for this purpose. And another method ExtractValuesFromCell is also entertained to achieve the goal. It would be very interesting to throw a little light upon both of them.

Naturally I am familiar with the FindControl method of the datacontrols. For example, to find a dropdownlist in the formview or detailsview control, I would call:

DropDownList ddlTest=FormView1.FindControl("DropDownList1") as DropDownList;

Similarly, we could search for an asp.net control in a particular row of a gridview control. For example:

GridViewRow row=GridView1.Rows[5]; // here we are dealing with the fifth row
TextBox textName=row.Cells[2].FindControl("textboxName") as TextBox; //here, there is a textbox with id textboxName in the second cell of the row
if(textName!=null) //check if such textbox was found in the specified cell or the specified row
{
string name=textName.Text;
}

Practically we need to get a control from the data control in special events of the control like inserting, inserted, updating, updated, deleting, deleted, selectedindexchanging, selectedindexchanged etc. Combining the FindControl method with such event handlers help customize data during data operations (add,edit,delete) and provides flexibility to display data from database or other data sources (xml, csv, programmatically created datatables etc).

Before discussing ExtractValuesFromCell, I would like to drop one note. Please note that some standard controls in some data controls may be available for extracting only in the particular mode of the data controls. Confusing? Don't worry. This simple example will clarify it. Say, we do have a textbox in the edititemtemplate of a detailsview. To reference this textbox and extract value from it, we can use the findcontrol method only if we are in edit mode. In other modes we will get null reference (and possibly null reference exception may be thrown when we try to extract text or other properties). That is why I have checked for the null in the code above before reading text value from the textbox.

Now let's focus on ExtractValuesFromCell. There goes a popular article on Extracting data out of your datacontrol which discusses ExtractValuesFromCell method to get data from the controls in datacontrols like gridview, formview or detailsview. (The title of this article is inspired from it! And I have tried to make it as useful as I can). Please refer to the heavily discussed article to understand what the author davidfoul has discovered and what are the benefits of using ExtractValuesFromCell method to extract data out of a datacontrol.

After you have been through the article, you sure would like to ask which method to use- FindControl or this ExtractValuesFromCell? This is what I commented to the author:

Hi dear author,

I came here following the discussion on the asp.net forum: forums.asp.net/.../1362718.aspx

I have always been using FindControl() method: much easier and handy. You need not to write (and call everytime) the functions to extract values (or cells) using ExtractValuesFromCell.

This ExtractValuesFromCell way of extracting values from cell is just another way around it. So what's wrong to go with FindControl. Please give your opinion (perhaps you could update the post to add a sections: Why to not use FindControl(); I am requesting this because the argument among developers would go longer!).

Hey, this could be the advantage: People sometimes ask how to get all the values from my gridview since I have been editing and updating it, so changing the original value from the datasource. In such case this trick could help a lot.

Thanks.

And our generous author davidfoul has replied his kind views:

@sangam100 I had this same question about FindControl on the forum. Here is what I said:

It's not the use of FindControl that makes my spine tingle its the MISuse and ABuse of it that does. FindControl is a good method and very useful, but look at the name of method, FindControl. Everything has a purpose right? If I'm trying to find a control then i'll call find control. If I'm trying to get data out of a control I might call find control or some other API that is better at getting data, i.e ExtractRowValues. I think that there is alot of knowledge out there, good and bad, about using these data controls and I just want to try to set some things straight by shedding some more light on how stuff works (I love that website).

Before I go lemme show you what I mean by picking the right API.  Lets make a new control IntControl. IntControl has a method int GetValue(). Now OO principals tell us to not break the abstraction by letting consumers grab at the internals but IntControl derives from control, and by default, there is alot of other things exposed to the consumer that shouldn't be. Now we know that IntControl uses a textbox internally so I could never call GetValue and instead write:

int value;

Int32.TryParse(((TextBox)IntControl.Controls[0]).Text, out value);

Everything will work fine until the author of IntControl decides to use a div instead of a textbox.

The REAL lesson to take away from the blog post is to try your best to follow the contract provided by a class or an interface (in this case the DataControl).

You can read comments, views, suggestions of so many enthusiastic asp.net web developers both in the original site by the author and a post in the forums.asp.net/.../1362718.aspx. Please comment in the respective sites to put your opinions to the articles. However you can comment as always on this article regarding my perspectives. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

| 0 comments ]

Sending email in asp.net is very useful and customizable too. The powerful classes help you compose and send email in minute! The glamour has always fascinated me, but more important is the frequent questions that are asked in asp.net related forums on sending email in asp.net using C# or vb.net. We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email (Thank you gmail!)

Take one example- Here goes the question that was asked in asp.net forum-

"can someone give me code how to send an e-mail from c# code
I am working with a company using Microsoft outlook for my mails.
I want to send mail only to 1 person, also please help me in identifying "smtp hostname"
"

Here goes the simple and helpful answer.

Visiting all above listed links you must have realized that sending email in asp.net is quite fun and useful too. In fact, a lot of customizations exist depending on your requirement. My suggestion is to do the basic email sending first. After that you can play with the classes and objects to perform more actions. Let me show you the basic email sending using c#.

//sending basic mail in asp.net 
public void SendBasicMail()
{
//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress("sangam@test.com"), new MailAddress("anup@best.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient("mail.mysmtpserver.com", 25);
try
{
client.Send(message);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
}
}

This simple example will help you understand the basics of sending email in asp.net web application.

Now interested in sending email using our own gmail account? Here goes the coding by getchinna_sv (Thank you getchinna_sv! Yours sangam100).

 protected void sendMail()
{
string from = "me@gmail.com"; //Replace this with your own correct Gmail Address
string to = "you@gmail.com"; //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "One Ghost", System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
HttpContext.Current.Response.Write(errorMessage);
} // end try
}

client.Credentials = new System.Net.NetworkCredential(from, "Password"); in this statement... write your gmail password.... from address should be a gmail address....

Hope this post will help. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

| 1 comments ]

Today I got across a question in the asp.net forum which seems simple but is still confusing for many beginners. So I am giving a place for it here:

Question:

Hi Everyone,

I'm trying to set some error handling by returning a message when a button is clicked and the user has not selected an item from the dropdown menu. I'm using this but for some reason it is being ignored?

protected void validatebtn_Click(object sender, ImageClickEventArgs e)
{
if (!(DropDownList1.SelectedValue == "Select Item"))
{
lblerrors.Text = "
You have not selected an item from the drop down list.";
}
else
{
//...continue with the code.
}
}

When I debug the code, it reads the first line:

if (!(DropDownList1.SelectedValue == "Select Item"))
and then skips to the else statement and misses my message?

Can anyone advise why this is happening?

Thanks.
Chloe ~X~

Among other suggestions, here is what I have suggested:

Answer:

Looking into your explanation and reading all the answers given by members, some questions came in my mind.

1. Did you check what value is exactly selected from the dropdownlist? I mean DropDownList1.SelectedValue should be "Select Item" only then your comparision will be true.
2. Are you adding this "Select Item" from design view or is it added programmatically from code behind? Did you only specify "text" or both text and value? See the markup below:

<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Text="Select Item" Value="Select Item" Selected="True"></asp:ListItem>
</asp:DropDownList>

If you don't put Selected="true", this item may display at the first position, but is not selected yet. So don't forget to set this. Another thing to notice is you should have set both Text and Value. The "SelectedValue" corresponds to the "Value" in the markup. Only then your code will work. Don't forget to have both text and value if you add listitem to the dropdownlist from codebehind, like this one:

ListItem item = new ListItem("Select Item", "Select Item");
DropDownList1.Items.Add(item);

Hope this helps. Please feel free to ask if the problem persists or if further help is required. Thanks.

kick it on DotNetKicks.com Shout it pimp it

| 0 comments ]

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

| 1 comments ]

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