Wrox Home  
Search P2P Archive for: Go

  Return to Index  

aspx_professional thread: FW: Datagrid Client side events for the dynamically created edit controls!!


Message #1 by "Tim Cartwright" <tcartwright@t...> on Sat, 30 Mar 2002 13:26:34 -0600
Ok, received this message after sending you the email with the attachment.
So here comes the code.....

A message bearing an attachment, or several attachments has been recieved
from this address by the mailing lists run by Wrox Press at
http://p2p.wrox.com
Our policy is not to accept mail messages with attachments, owing to the
possibility that damaging files could be sent out to our mail recipients.
If the attachment was a code-snippet, please just cut&paste the code
straight into the body of your message and resubmit your message. We're
sorry for this inconvenience, but we do hope you understand our reasons.
Daniel Walker
Wrox Press

****************************************************************************
*********************************
WebForm1.aspx
****************************************************************************
*********************************
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb"
Inherits="Testing2.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
		<title>WebForm1</title>
		<meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
		<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
		<script language="javascript">
		<!--
		function handlePress(e) {
			/*Limit input for username to A-Za-z0-9

			This could prolly be converted to the regex, but I am unsure of the regex
			being multi browser compatible, and was shooting for simplicity

			hmmmm, I COULD handle this on the server, but then I would be even more
dumb than I look :P
			*/
			var whichCode = (window.Event) ? e.which : e.keyCode;
			bFail = !(whichCode < 48 || whichCode > 57) || !(whichCode < 65 ||
whichCode > 90) || !(whichCode < 97 || whichCode > 122);
			e.returnValue = bFail;
			return bFail;
		}
		//-->
		</script>
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 105px; POSITION:
absolute; TOP: 45px" runat="server" Width="791px" Height="100px"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" BackColor="White"
CellPadding="4" AutoGenerateColumns="False">
				<SelectedItemStyle Font-Bold="True" ForeColor="#CCFF99"
BackColor="#009999"></SelectedItemStyle>
				<ItemStyle ForeColor="#003399" BackColor="White"></ItemStyle>
				<HeaderStyle Font-Bold="True" ForeColor="#CCCCFF"
BackColor="#003399"></HeaderStyle>
				<FooterStyle ForeColor="#003399" BackColor="#99CCCC"></FooterStyle>
				<Columns>
					<asp:BoundColumn DataField="FirstName" HeaderText="First
Name"></asp:BoundColumn>
					<asp:BoundColumn DataField="LastName" HeaderText="Last
Name"></asp:BoundColumn>
					<asp:BoundColumn DataField="UserName" HeaderText="User
Name"></asp:BoundColumn>
				</Columns>
				<PagerStyle HorizontalAlign="Left" ForeColor="#003399"
BackColor="#99CCCC" Mode="NumericPages"></PagerStyle>
			</asp:datagrid>
			<asp:Button id="cmdAddNew" style="Z-INDEX: 102; LEFT: 108px; POSITION:
absolute; TOP: 14px" runat="server" Text="Add New"></asp:Button></form>
	</body>
</HTML>
****************************************************************************
*********************************
END WebForm1.aspx
****************************************************************************
*********************************

****************************************************************************
*********************************
WebForm1.aspx.vb
****************************************************************************
*********************************
Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub
InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Dim mobjDataView As DataView
    Protected WithEvents cmdAddNew As System.Web.UI.WebControls.Button
    Dim mobjDataTable As DataTable

    Private Enum ColumnsOrderEnum
        FirstName = 0
        LastName = 1
        UserName = 2
    End Enum

    Private Function GetDs() As DataSet
        Dim ds As New DataSet()
        ds.ReadXml(Server.MapPath(".") & "\Users.xml")
        Return ds
    End Function

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

        mobjDataTable = New DataTable()

        If Session("Ds") Is Nothing Then
            Session.Add("Ds", GetDs())
        End If

        mobjDataTable = CType(Session("Ds"), DataSet).Tables(0)
        mobjDataView = New DataView(mobjDataTable)

        If Not IsPostBack Then
            DataGrid1.DataSource = mobjDataView
            DataGrid1.DataBind()
        End If
    End Sub

    Private Sub cmdAddNew_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdAddNew.Click
        Dim objRow As DataRow

        mobjDataTable.BeginLoadData()
        objRow = mobjDataTable.NewRow()
        objRow("FirstName") = "First Name"
        objRow("LastName") = "Last Name"
        objRow("UserName") = ""
        mobjDataTable.EndLoadData()

        mobjDataTable.Rows.Add(objRow)

        DataGrid1.EditItemIndex = mobjDataTable.Rows.Count - 1
        DataGrid1.DataSource = mobjDataView
        DataGrid1.DataBind()
    End Sub

    Private Sub DataGrid1_ItemCreated(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataGridItemEventArgs) Handles
DataGrid1.ItemCreated
        If e.Item.ItemIndex <> -1 Then 'ignore the page rows
            If e.Item.Cells(ColumnsOrderEnum.FirstName).HasControls Then
                'the datagrid follows this convention when creating rows :

                '{Name Of Grid}:_ctl{row number}:_ctl{control number}

                'Row number - have to account for the page, and header rows,
                'hence the + 3 as rows are zero based, and I am showing the
top page row, AND the header row
                'If not showing thse rows, the number must be modified
accordingly

                'Control Number - this IS the control number for this row,
which may or may not match up to the
                'cell number, from what I can gather, it only has a control
for the button columns and editable columns

                '(kinda makes sense but was a pain to figure out)
                Dim intAddRows As Integer = 1
                If DataGrid1.PagerStyle.Position = PagerPosition.Top Or
DataGrid1.PagerStyle.Position = PagerPosition.TopAndBottom Then
                    intAddRows += 1
                End If
                If DataGrid1.ShowHeader Then
                    intAddRows += 1
                End If
                Dim strDGRow As String = "DataGrid1:_ctl" &
(e.Item.ItemIndex + intAddRows) & ":_ctl"

                'this line MUST be modified if ever the grid design changes
(ESPECIALLY THE COLUMN ORDER AS I AM HARD CODING THE ORDER :( )
                'add the event handler to auto input the username
                Dim strKeyUp As String = "var sFName = Form1.all(""" &
strDGRow & ColumnsOrderEnum.FirstName & """).value;" & _
                    "var sLName = Form1.all(""" & strDGRow &
ColumnsOrderEnum.LastName & """).value;" & _
                    "Form1.all(""" & strDGRow & ColumnsOrderEnum.UserName &
""").value = sFName.substr(0, 1) + sLName.substr(0);return true;"

                CType(e.Item.Cells(1).Controls(0),
TextBox).Attributes.Add("onkeyup", strKeyUp)

                'restrict username keypress to A-Z, a-z, 0-9
                CType(e.Item.Cells(ColumnsOrderEnum.UserName).Controls(0),
TextBox).Attributes.Add("onkeypress", "return handlePress(event);")
            End If
        End If
    End Sub
End Class
****************************************************************************
*********************************
END WebForm1.aspx.vb
****************************************************************************
*********************************

****************************************************************************
*********************************
Users.xml
****************************************************************************
*********************************
<Users xmlns="http://tempuri.org/Users.xsd">
	<User>
		<FirstName>Tim</FirstName>
		<LastName>Cartwright</LastName>
		<UserName>Tcartwright</UserName>
	</User>
	<User>
		<FirstName>John</FirstName>
		<LastName>Smith</LastName>
		<UserName>Jsmith</UserName>
	</User>
	<User>
		<FirstName>Jane</FirstName>
		<LastName>Doe</LastName>
		<UserName>JDoe</UserName>
	</User>
</Users>
****************************************************************************
*********************************
END Users.xml
****************************************************************************
*********************************

****************************************************************************
*********************************
Users.xsd
****************************************************************************
*********************************
<?xml version="1.0" ?>
<xs:schema id="Users" targetNamespace="http://tempuri.org/Users.xsd"
xmlns:mstns="http://tempuri.org/Users.xsd"
xmlns="http://tempuri.org/Users.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
attributeFormDefault="qualified" elementFormDefault="qualified">
	<xs:element name="Users" msdata:IsDataSet="true"
msdata:EnforceConstraints="False">
		<xs:complexType>
			<xs:choice maxOccurs="unbounded">
				<xs:element name="User">
					<xs:complexType>
						<xs:sequence>
							<xs:element name="FirstName" type="xs:string" minOccurs="0" />
							<xs:element name="LastName" type="xs:string" minOccurs="0" />
							<xs:element name="UserName" type="xs:string" minOccurs="0" />
						</xs:sequence>
					</xs:complexType>
				</xs:element>
			</xs:choice>
		</xs:complexType>
	</xs:element>
</xs:schema>
****************************************************************************
*********************************
END Users.xsd
****************************************************************************
*********************************

Tim Cartwright //Will write code for food
Sr. Systems Engineer
The System Shop Inc.
xxx-xxx-xxxx
-----Original Message-----
From: Tim Cartwright [mailto:tcartwright@t...]
Sent: Saturday, March 30, 2002 13:08
To: aspx_professional@p...
Subject: Datagrid Client side events for the dynamically created controls!!


Recently I was writing an aspx datagrid to manage users, and on the creation
of a new user I wanted to add client side script for the keypress event for
the lastname so that it would take the first initial + lastname and default
the username to that. I have attached a sample project, and the code of
interest is in : "DataGrid1_ItemCreated" in the "WebForm1.aspx.vb" file.
This technique can be applied to add client side events for editing or
adding. I have zipped up and attached a sample project. Please let me know
if there is anything else that I can provide.

I wrote this as an example so there are many things I left out for the sake
of trying to keep the code simple :

Exception handling
Database interaction
Editing
Sorting, Paging

My whole purpose of this example is to demonstrate the capability to attach
an event to the dynamically created controls that the aspx engine generates
for you when editing or adding a new item to a datagrid.

Tim Cartwright //Will write code for food
Sr. Systems Engineer
The System Shop Inc.
xxx-xxx-xxxx


  Return to Index