WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

GridView 上の DropDownList に ToolTip

by WebSurfer 2013年11月2日 18:33
注意:
以下の記事の例では、Products テーブルの CategoryID が NULL の場合、および更新の際に NULL を入力する場合の対応は考えていません。NULL 対応は別の記事 DropDownList での NULL の処置 を見てください。

GridView などで更新操作を行う際、DropDownList を利用してユーザー入力に便宜を図ることがあります。その際、ツールチップを利用して DropDownList 上の各項目の説明を表示するという話です。

GridView 上の DropDownList に ToolTip 表示

ここで紹介する例には Microsoft が提供している Northwind サンプルデータベースの Products テーブルと Categories テーブルを使用しています。

Products テーブルの中の ProductName, CategoryID フィールドを GridView 上で更新する際、CategoryID の列に DropDownList を表示するようにします。

DropDownList には、ユーザーが見ても何だか分からない ID (CategoryID) を表示するのでははなくて、ユーザーが読んで理解できる名前 (CategoryName) を表示します。

さらに DropDownList を開いて項目一覧を表示し、それにマウスカーソルを当てると各項目の説明 (Description) をツールチップに表示するようにします。上の画像を見てください。

DropDownList が閉じている時に DropDownList にマウスカーソルを当てると、選択された項目の説明がツールチップに表示されるようにしています。

上の画像を表示したサンプルコードは以下の通りです。詳細はコメントに説明を書きましたので、それを参考にしてください。手抜きでスミマセン。(汗)

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  // DropDownList には RowDataBound や ItemDataBound に該当す
  // るイベントがないので、各項目にツールチップを追加するには
  // 以下のような方法を取らざるを得ない。
  // 
  // GridView の[編集]ボタンがクリックされるとポストバック
  // され、当該行内に DropDownList がレンダリングされる。その
  // 際に DropDownList.DataBound イベントが発生するので、そこ
  // で DropDownList およびその中の ListItem にツールチップを
  // 設定する。
  protected void DropDownList1_DataBound(object sender, 
        EventArgs e)
  {
      DropDownList ddl = (DropDownList)sender;

      // 再度 DB にクエリを投げてデータを取得。(他に方法が
      // 見つからない)
      DataView dv = (DataView)SqlDataSource2.
            Select(DataSourceSelectArguments.Empty);

      foreach (ListItem item in ddl.Items)
      {
          dv.RowFilter = 
                String.Format("CategoryID='{0}'", item.Value);
          string description = (string)dv[0]["Description"];
            
          // ListItem には ToolTip プロパティはないので、直接
          // title 属性に description を設定する。
          item.Attributes["title"] = description;

          // DropDownList の ToolTip には、選択されている項目の
          // description を設定する。
          if (item.Selected)
          {
              ddl.ToolTip = description;
          }
      }

      // ユーザーが DropDownList 中の項目をクリックして選択され
      // ている項目を変更した場合、それに応じて DropDownList の
      // ToolTip を書き換えるためのスクリプトを追加        
      string csname1 = "jQuery1.8.3";
      string csurl = "~/Scripts/jquery-1.8.3.js";
      string csname2 = "ChangeDropDownListToolTipScript";
      Type cstype = this.GetType();
      ClientScriptManager cs = Page.ClientScript;

      // jQuery を利用するので参照を追加。
      if (!cs.IsClientScriptIncludeRegistered(cstype, csname1))
      {
          cs.RegisterClientScriptInclude(
                cstype, csname1, ResolveClientUrl(csurl));
      }

      // DropDownList の ToolTip 書き換え用スクリプト追加。
      if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
      {
          StringBuilder cstext = new StringBuilder();
          cstext.Append("$(function () {");
          cstext.Append("$('#" + ddl.ClientID + "').change(");
          cstext.Append("function () {");
          cstext.Append("$(this).attr('title', $('#" +
                ddl.ClientID +
                " option:selected').attr('title'));");
          cstext.Append("});");
          cstext.Append("});");
          cs.RegisterClientScriptBlock(
              cstype, csname2, cstext.ToString(), true);
      }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:SqlDataSource ID="SqlDataSource1" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:Northwind %>" 
      SelectCommand=
        "SELECT TOP 10 
          p.[ProductID], p.[ProductName], 
          p.[CategoryID], c.[CategoryName] 
        FROM [Products] AS p 
        INNER JOIN [Categories] AS c 
        ON p.[CategoryID] = c.[CategoryID] 
        ORDER BY p.[ProductID]" 
      UpdateCommand=
        "UPDATE [Products] 
        SET [ProductName] = @ProductName, 
            [CategoryID] = @CategoryID 
        WHERE [ProductID] = @ProductID">
      <UpdateParameters>
        <asp:Parameter Name="ProductID" Type="Int32" />
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="CategoryID" Type="Int32" />                
      </UpdateParameters>
    </asp:SqlDataSource>

    <asp:SqlDataSource ID="SqlDataSource2" 
      runat="server" 
      ConnectionString="<%$ ConnectionStrings:Northwind %>" 
      SelectCommand=
        "SELECT [CategoryID], [CategoryName], [Description] 
        FROM [Categories]">
    </asp:SqlDataSource>
        
    <asp:GridView ID="GridView1" 
      runat="server" 
      AutoGenerateColumns="False" 
      DataKeyNames="ProductID" 
      DataSourceID="SqlDataSource1">
      <Columns>
        <asp:CommandField ShowEditButton="True" />
        <asp:BoundField DataField="ProductID" 
          HeaderText="ID" 
          InsertVisible="False" 
          ReadOnly="True" 
          SortExpression="ProductID" />
        <asp:BoundField DataField="ProductName" 
          HeaderText="Product Name" 
          SortExpression="ProductName" />
        <asp:TemplateField HeaderText="Category" 
          SortExpression="CategoryName">
          <EditItemTemplate>                        
            <asp:DropDownList ID="DropDownList1" 
              runat="server" 
              DataSourceID="SqlDataSource2" 
              DataTextField="CategoryName" 
              DataValueField="CategoryID" 
              SelectedValue='<%# Bind("CategoryID") %>' 
              OnDataBound="DropDownList1_DataBound">
            </asp:DropDownList>
          </EditItemTemplate>
          <ItemTemplate>
            <asp:Label ID="Label1" 
              runat="server" 
              Text='<%# Bind("CategoryName") %>'>
            </asp:Label>
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
    </asp:GridView>
  </div>
  </form>
</body>
</html>

Tags: , ,

ASP.NET

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2024年4月  >>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

View posts in large calendar