In the ASP.Net FileUpload Control user can type in text also they can paste some text and click upload button which then causes an unnecessary server side call, hence many asked on forums on how to disable or prevent users from typing and pasting of text in the FileUpload Control. So here is the tip.
Consider the FileUpload Control below which does it for you
<asp:FileUpload ID="FileUpload1" runat="server"
onkeydown = "return (event.keyCode==9);"
onpaste = "return false;" />
As you will notice I have added the following code on KeyDown event of FileUpload
onkeydown = "return (event.keyCode==9);"
The above JavaScript snippet checks if the key pressed is a Tab key (keyCode=9) and returns its result back to the KeyDown event. So whenever TAB key is pressed the conditions is satisfied and hence the TAB key works with the control if some other key other than TAB key is pressed then the condition is false hence it simply produces nothing
onpaste = "return false;"
This event is self explanatory disables pasting of any text inside the FileUpload Control.
When you add the two events to aspx page directly Visual Studio produces warning which is not an issue to worry since these are client side events and Visual Studio checks for Server Side events still if you do not want that to happen you can add the same from code behind too in the following way
C#
FileUpload1.Attributes.Add("onkeydown", "return (event.keyCode==9);");
FileUpload1.Attributes.Add("onpaste", "return false;");
VB.Net
FileUpload2.Attributes.Add("onkeydown", "return (event.keyCode==9);")
FileUpload2.Attributes.Add("onpaste", "return false;")
This completes the article. You can download the sample code using the link below.
DisableTypingPastingFileUpload.zip (2.92 kb)