- Clearing Text Box value by getting all the control in an ASP.NET Page with A MasterPage :
ContentPlaceHolder cp=(ContentPlaceHolder)this.Page.Master.FindControl("ContentPlaceHolder1");
clearTextbox(cp);
public void clearTextbox(Control parent)
{
foreach (Control T in parent.Controls)
{
if (T is TextBox)
{
var tb = T as TextBox;
tb.Text = "";
}
clearTextbox(T);
}
}
- Example: Allow only numbers/digits in TextBox
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
</BODY>
</HTML>
For many reasons sometime we don't want to allow user to use right click to copy paste or by using ctrl+C , ctrl+v to copy and paste in textbox on a aspx page in asp.net
Introduction
We can use javascript to disable right mouse click or ctrl keys to ensure user is not able to copy paste in a textbox
we can achieve this in 2 ways
1. use this method when you don't want any alerts or message
we can achieve this in 2 ways
1. use this method when you don't want any alerts or message
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
2. If you want to show alerts than use this method instead
Right this javascript function in the head section of aspx page, in this function we are disabling right mouse click and ctrl keys
Right this javascript function in the head section of aspx page, in this function we are disabling right mouse click and ctrl keys
<head runat="server">
<title>Untitled Page</title>
<script language="javascript">
function DisableRightClick(event)
{
//For mouse right click
if (event.button==2)
{
alert("Right Clicking not allowed!");
}
}
function DisableCtrlKey(e)
{
var code = (document.all) ? event.keyCode:e.which;
var message = "Ctrl key functionality is disabled!";
// look for CTRL key press
if (parseInt(code)==17)
{
alert(message);
window.event.returnValue = false;
}
}
</script>
</head>
<title>Untitled Page</title>
<script language="javascript">
function DisableRightClick(event)
{
//For mouse right click
if (event.button==2)
{
alert("Right Clicking not allowed!");
}
}
function DisableCtrlKey(e)
{
var code = (document.all) ? event.keyCode:e.which;
var message = "Ctrl key functionality is disabled!";
// look for CTRL key press
if (parseInt(code)==17)
{
alert(message);
window.event.returnValue = false;
}
}
</script>
</head>
Now use this function on the textbox which we want to disable copy paste and right clicking
<body>
<form id="form1" runat="server">
<div>
<strong>
Right click disabled</strong> textbox
<br />
<asp:TextBox ID="TextBoxCopy" runat="server"
onMouseDown="DisableRightClick(event)">
</asp:TextBox><br />
<br />
<strong>Ctrl key </strong>disabled<br />
<asp:TextBox ID="TextBox2" runat="server"
onKeyDown="return DisableCtrlKey(event)">
</asp:TextBox><br />
<br />
Another method to disable<strong> Cut,Copy and paste
</strong>in textbox<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
</form>
</body>
<form id="form1" runat="server">
<div>
<strong>
Right click disabled</strong> textbox
<br />
<asp:TextBox ID="TextBoxCopy" runat="server"
onMouseDown="DisableRightClick(event)">
</asp:TextBox><br />
<br />
<strong>Ctrl key </strong>disabled<br />
<asp:TextBox ID="TextBox2" runat="server"
onKeyDown="return DisableCtrlKey(event)">
</asp:TextBox><br />
<br />
Another method to disable<strong> Cut,Copy and paste
</strong>in textbox<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
</form>
</body>
decimalVar.ToString ("#.##");
- Hi there... You can modify below regular expression according to your need... the regex below will allow 5 digits with 2 decimal points
Expression: | (?!^0*$)(?!^0*\.0*$)^\d{1,5}(\.\d{1,2})?$ |
Description: | validates to 5 digits and 2 decimal places but not allowing zero |
Matches: | 12345.12|||0.5 |
Non-Matches: | 123456.12|||1.234|||.1 |
- Date Must be less than or equal to today’s date using range validator(N.B.date format in dd/mm/yyyy)
Ø Use one range validator and set its minimum value as 01-01-0001
Ø set its maximum value like below. In coding page’s pageload
Ø RangeValidator1.MaximumValue = string.Format("{0:dd/MM/yyyy}", DateTime.Today.ToShortDateString());
Ø Use ajax calender extender for date which will be easy while checking of dates.
- ContextKey not working in AutoCompleteExtender
Ø Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer, ByVal ContextKey As String) As String()
Ø Please use ByVal contextKey As String) As String() instead of ContextKey. It is recommended that you should save your web.config without any modifications before you debug it if you have done some changes to the WebService.
- Passing value from popup window to parent form's TextBox
Ø Passing values from a popup window back to the parent page is an often asked question. Especially when there is a GridView type control in the popup. In the following example we will be using two forms. The parent form will be parent.aspx and the popup will be popup.aspx. Also note that the parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.
--- .aspx of parent form ---
<script type="text/javascript">
function OpenPopup() {
window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
return false;
}
</script>
.
.
.
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show List" />
--- .vb of parent.aspx if vb.net is the language ---
If Not IsPostBack Then
Me.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()")
End If
--- .cs of parent.aspx if C#.net is the language ---
if (!IsPostBack) {
this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}
--- .aspx of popup form ---
<script language="javascript">
function GetRowValue(val)
{
// hardcoded value used to minimize the code.
// ControlID can instead be passed as query string to the popup window
window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
window.close();
}
</script>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
--- .vb file if vb.net is the language ---
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
'assuming that the required value column is the second column in gridview
DirectCast(e.Row.FindControl("btnSelect"), Button).Attributes.Add("onclick", "javascript:GetRowValue('" & e.Row.Cells(1).Text & "')")
End If
End Sub
--- .cs file if C#.net is the language ---
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
if ((e.Row.RowType == DataControlRowType.DataRow)) {
//assuming that the required value column is the second column in gridview
((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells[1].Text + "')");
}
}
- GridView with RadioButton – Select One at a Time
Introduction
Sometimes, we will have requirements to have a RadioButton control in every row of the GridView control to select one row at a time. If we have a TemplateColumn with a RadioButton control, it will allow selection of multiple rows by default. This is because, the RadioButton will have different ID for every row and hence it will allow multiple selections. So, we should add some sort of client side functionality that prevents selection of multiple Radio Buttons but one. In this article, we will call a Javascript function on click of RadioButton that checks if there is some other RadioButton in the GridView is already selected to uncheck it leaving the current selection.
First Method using javascript: Steps Declare a GridView control with a TemplateColumn as the first column to include Radio control. Include BoundField for other fields to display in the GridView. <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4" OnRowCommand="gvUsers_RowCommand"> <Columns> <asp:TemplateField HeaderText="Select"> <ItemTemplate> <asp:RadioButton ID="rdbGVRow" onclick="javascript:CheckOtherIsCheckedByGVID(this);" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" /> <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" /> <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" /> </Columns> <FooterStyle BackColor="White" ForeColor="#330099" /> <RowStyle BackColor="White" ForeColor="#330099" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" /> <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" /> <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" /> </asp:GridView> CodeBehind protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) BindUsers(); } public void BindUsers() { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString); con.Open(); SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con); com.CommandType = CommandType.StoredProcedure; SqlDataAdapter ada = new SqlDataAdapter(com); DataTable dt = new DataTable(); ada.Fill(dt); gvUsers.DataSource = dt; gvUsers.DataBind(); } Execute the page. You can see the GridView with RadioButton. Adding Client Side Functionality To check if there is some other row selected and to uncheck it by keeping the current row selection we will call a JavaScript function called CheckOtherIsCheckedByGVID(). This function is called by the OnClick event of the RadioButton, Refer the above code. The below JavaScript function will do our client side functionality. function CheckOtherIsCheckedByGVID(spanChk) { var IsChecked = spanChk.checked; if(IsChecked) { spanChk.parentElement.parentElement.style.backgroundColor='#228b22'; spanChk.parentElement.parentElement.style.color='white'; } var CurrentRdbID = spanChk.id; var Chk = spanChk; Parent = document.getElementById('gvUsers'); var items = Parent.getElementsByTagName('input'); for(i=0;i<items.length;i++) { if(items[i].id != CurrentRdbID && items[i].type=="radio") { if(items[i].checked) { items[i].checked = false; items[i].parentElement.parentElement.style.backgroundColor='white'; items[i].parentElement.parentElement.style.color='black'; } } } } | |
Execute the page and see it in action. Since, we are getting all the elements with tag name as “input”, the above code will uncheck if there are any other RadioButton control is present in any other column for a different purpose. To understand it better, include one more TemplateField with RadioButton control at the last in the GridView columns list and test it. To handle the above scenario with multiple RadioButton in a Row, we will change the code a bit to access the RadioButton based on the column location. If we see the rendered table in the HTML output, we will have the RadioButton at every first TD. The below code will clear the selection of RadioButton that is found only in the first column. function CheckOtherIsCheckedByGVIDMore(spanChk) { var IsChecked = spanChk.checked; if(IsChecked) { spanChk.parentElement.parentElement.style.backgroundColor='#228b22'; spanChk.parentElement.parentElement.style.color='white'; } var CurrentRdbID = spanChk.id; var Chk = spanChk; Parent = document.getElementById('gvUsers'); for(i=0;i< Parent.rows.length;i++) { var tr = Parent.rows[i]; var td = tr.childNodes[0]; var item = td.firstChild; if(item.id != CurrentRdbID && item.type=="radio") { if(item.checked) { item.checked = false; item.parentElement.parentElement.style.backgroundColor='white'; item.parentElement.parentElement.style.color='black'; } } } } The above code assumes the RadioButton will be the first column of every row in the GridView. This code will work perfectly even if there are RadioButton present in any other column of the GridView control. Second Method in Coding: |
protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
{
//Clear the existing selected row
foreach (GridViewRow oldrow in GridView1.Rows)
{
((RadioButton)oldrow.FindControl("rbSelector")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("rbSelector")).Checked = true;
}
{
//Clear the existing selected row
foreach (GridViewRow oldrow in GridView1.Rows)
{
((RadioButton)oldrow.FindControl("rbSelector")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("rbSelector")).Checked = true;
}
- Getting same column value from one table multiple times
e.g. one table name is Mas_branchoffice
Table Structure:
Branch_code | Branch_name |
5001 | Chennai |
5003 | Bhubaneswar |
Suppose Another table name is Trans_Stock_Transfer
Table Structure:
From_Branch_code | To_Branch_code | st_invoice_no | st_invoice_date | net_total |
5001 | 5003 | 2385 | 15/11/2010 | 9000 |
We have to display the details of Trans_Stock_Transfer table with branch name of the branch code present in Mas_StockTransfer table by fetching the name from Mas_Branchoffice using join.
From Branch Name | To Branch Name | st_invoice_no | st_invoice_date | net_total |
Chennai | Bhubaneswar | 2385 | 15/11/2010 | 9000 |
Soln:
select Trans_Stock_Transfer.st_invoice_no,Trans_Stock_Transfer.st_invoice_date,
MBranch1.branch_name,
MBranch2.branch_name,Trans_Stock_Transfer.net_total from Trans_Stock_Transfer
left join Mas_Branchoffice as MBranch1 on Trans_Stock_Transfer.from_branch_code=MBranch1.branch_code
left join Mas_Branchoffice as MBranch2 on Trans_Stock_Transfer.to_branch_code=MBranch2.branch_code
- Creating SQL Server GUID(Global unique identification number)
Question: Write a SQL Stored Procedure to create a GUID and add it to a table. Make that GUID an OUTPUT of that Procedure
GUIDs are created by the newid() function. If the default of the primary key is set to NewID() a new GUID is generated for any new row. In addition the newid() function may be declared within an insert/values list. The newid() function will even work as an expression in an insert/select that selects multiple rows. Within stored procedures or front-end code the function may be called and the GUID stored in a variable. The variable is then used in the insert/values statement and inserted into the new row.
USE db_SUTANU
Create table TBL_USER(USER_ID UniqueIdentifier default NewId() USER_NAME nvarchar(50))
The next three queries insert a GUID each using a different method of generating the GUID:
-- GUID from Default (the columns default is NewID())
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (DEFAULT ‘Debasis’)
-- GUID from function
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (NewID() ‘SUTANU’)
-- GUID in variable
DECLARE @NewGUID UniqueIdentifier
SET @NewGUID NewID()
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (@NewGUID ‘Madhumita’)
To view the results of the previous three methods of inserting a GUID.
SELECT USER_ID USER_NAME
FROM db_SUTANU.dbo.[TBL_USER]
USER_ID USER_NAME
------------------------------------ -----------------------
25894DA7-B5BB-435D-9540-6B9207C6CF8F Debasis
393414DC-8611-4460-8FD3-4657E4B49373 SUTANU
FF868338-DF9A-4B8D-89B6-9C28293CA25F Madhumita
USE db_SUTANU
Create table TBL_USER(USER_ID UniqueIdentifier default NewId() USER_NAME nvarchar(50))
The next three queries insert a GUID each using a different method of generating the GUID:
-- GUID from Default (the columns default is NewID())
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (DEFAULT ‘Debasis’)
-- GUID from function
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (NewID() ‘SUTANU’)
-- GUID in variable
DECLARE @NewGUID UniqueIdentifier
SET @NewGUID NewID()
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID USER_NAME)
VALUES (@NewGUID ‘Madhumita’)
To view the results of the previous three methods of inserting a GUID.
SELECT USER_ID USER_NAME
FROM db_SUTANU.dbo.[TBL_USER]
USER_ID USER_NAME
------------------------------------ -----------------------
25894DA7-B5BB-435D-9540-6B9207C6CF8F Debasis
393414DC-8611-4460-8FD3-4657E4B49373 SUTANU
FF868338-DF9A-4B8D-89B6-9C28293CA25F Madhumita
- how to stop marquee on mouseover???
<marquee onmouseover="this.stop();" onmouseout="this.start();">
my text here
</marquee>
- SQL: UPDATE Statement
The UPDATE statement allows you to update a single record or multiple records in a table.
The syntax for the UPDATE statement is:
UPDATE table
SET column = expression
WHERE predicates;
SET column = expression
WHERE predicates;
Example #1 - Simple example
Let's take a look at a very simple example.
UPDATE suppliers
SET name = 'HP'
WHERE name = 'IBM';
SET name = 'HP'
WHERE name = 'IBM';
This statement would update all supplier names in the suppliers table from IBM to HP.
Example #2 - More complex example
You can also perform more complicated updates.
You may wish to update records in one table based on values in another table. Since you can't list more than one table in the UPDATE statement, you can use the EXISTS clause.
For example:
UPDATE suppliers SET supplier_name = ( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id) WHERE EXISTS
( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
FROM customers
WHERE customers.customer_id = suppliers.supplier_id) WHERE EXISTS
( SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
Whenever a supplier_id matched a customer_id value, the supplier_name would be overwritten to the customer name from the customers table.
Learn more about the EXISTS condition.
Practice Exercise #1:
Based on the suppliers table populated with the following data, update the city to "Santa Clara" for all records whose supplier_name is "NVIDIA".
CREATE TABLE suppliers ( supplier_id number(10) not null, supplier_name varchar2(50) not null, city varchar2(50), CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id) );
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'New York');
VALUES (5001, 'Microsoft', 'New York');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');
VALUES (5002, 'IBM', 'Chicago');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');
VALUES (5003, 'Red Hat', 'Detroit');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5004, 'NVIDIA', 'New York');
VALUES (5004, 'NVIDIA', 'New York');
Solution:
The following SQL statement would perform this update.
UPDATE suppliers
SET city = 'Santa Clara'
WHERE supplier_name = 'NVIDIA';
SET city = 'Santa Clara'
WHERE supplier_name = 'NVIDIA';
The suppliers table would now look like this:
SUPPLIER_ID | SUPPLIER_NAME | CITY |
5001 | Microsoft | New York |
5002 | IBM | Chicago |
5003 | Red Hat | Detroit |
5004 | NVIDIA | Santa Clara |
Practice Exercise #2(IMPortant):
Based on the suppliers and customers table populated with the following data, update the city in the suppliers table with the city in the customers table when the supplier_name in the suppliers table matches the customer_name in the customers table.
CREATE TABLE suppliers ( supplier_id number(10) not null, supplier_name varchar2(50) not null, city varchar2(50), CONSTRAINT suppliers_pk PRIMARY KEY (supplier_id) );
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5001, 'Microsoft', 'New York');
VALUES (5001, 'Microsoft', 'New York');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5002, 'IBM', 'Chicago');
VALUES (5002, 'IBM', 'Chicago');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5003, 'Red Hat', 'Detroit');
VALUES (5003, 'Red Hat', 'Detroit');
INSERT INTO suppliers (supplier_id, supplier_name, city)
VALUES (5005, 'NVIDIA', 'LA');
VALUES (5005, 'NVIDIA', 'LA');
CREATE TABLE customers ( customer_id number(10) not null, customer_name varchar2(50) not null, city varchar2(50), CONSTRAINT customers_pk PRIMARY KEY (customer_id) );
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7001, 'Microsoft', 'San Francisco');
VALUES (7001, 'Microsoft', 'San Francisco');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7002, 'IBM', 'Toronto');
VALUES (7002, 'IBM', 'Toronto');
INSERT INTO customers (customer_id, customer_name, city)
VALUES (7003, 'Red Hat', 'Newark');
VALUES (7003, 'Red Hat', 'Newark');
Solution:
The following SQL statement would perform this update.
UPDATE suppliers SET city = ( SELECT customers.city
FROM customers
WHERE customers.customer_name = suppliers.supplier_name) WHERE EXISTS
( SELECT customers.city
FROM customers
WHERE customers.customer_name = suppliers.supplier_name);
FROM customers
WHERE customers.customer_name = suppliers.supplier_name) WHERE EXISTS
( SELECT customers.city
FROM customers
WHERE customers.customer_name = suppliers.supplier_name);
The suppliers table would now look like this:
SUPPLIER_ID | SUPPLIER_NAME | CITY |
5001 | Microsoft | San Francisco |
5002 | IBM | Toronto |
5003 | Red Hat | Newark |
5004 | NVIDIA | LA |
- How to expand and collapse code block (regions) in Visual Studio?
Ctrl+M+L to toggle all (collapse and explore) code block.
Ctrl+M+O to collapse region block
Ctrl+M+P to expand code block
Ctrl+M+O to collapse region block
Ctrl+M+P to expand code block
No comments:
Post a Comment