Wednesday, January 2, 2013
Handling Row Selection in a Data View

The key of the selected row of a data view can be accessed using JavaScript.

Start the Project Designer. On the Project Explorer toolbar, click on the New Page icon.

Creating a new page in the Project Explorer.

Use these values for the new page:

Property Value
Name ProductsTest
Roles n/a

Press OK to save. In the Project Explorer, drop Products Test page node on the right side of Home page node to place it second in the hierarchy.

Dropping page 'Products Test' on the right side of 'Home'.     Page 'Products Test' has been placed second in the list of pages.

Right-click on Products Test node, and press New Container.

Creating a new container in the page.

Use the default values and press OK to save.

Right-click on Products Test / c101 container node, and press New Control.

Creating a new control in the container.

Next to the User Control property, click on the New User Control icon.

Activating the 'New User Control' icon.

Assign a name to the user control:

Property Value
Name SelectedKeyBox

Press OK to save and insert it into the User Control property. Press OK again to add the control to the page.

Next, switch to the Controllers tab. Right-click on Products controller and press Copy.

Using the 'Copy' context menu option for Products controller.

Switch back to the Pages tab. Right-click on Products Test / c101 container node, and press Paste. A Products data view will be instantiated.

Pasting onto the container in Products Test page.     Products data controller instantiated as a data view.

On the toolbar, press Browse to generate the user control file. When done, right-click on Products Test / c101 / control1 – SelectedKeyBox node and press Edit in Visual Studio.

Editing the user control in Visual Studio.

The file will be opened in Visual Studio. Replace the code after the <%@ Control %> element with the following:

<script type="text/javascript">
    $(window).ready(
    setTimeout(function () {
        var dataView = Web.DataView.find('Products', 'Controller');
        if (dataView)
            dataView.add_selected(function () {
                $('.MyTextBox').val(dataView.get_selectedKey())
            });
    }, 50)
    );
</script>
<asp:TextBox type="text" ID="TextBox1" runat="server" class="MyTextBox"></asp:TextBox>

The user control will consist of an empty textbox. When the user selects a row, the selected key will be assigned as the value of the textbox.

Save the file. Switch to the open browser tab with the web app. Refresh the page, and navigate to Products Test page.

A textbox will be present above the list of products. Click on a row, and the ProductID will be displayed in the textbox.

The ProductID of the selected row is displayed in the textbox.

Clicking on another row will update the value in the textbox.

Clicking on another row will update the textbox.