65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET DataGrid 多列下拉列表

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.46/5 (35投票s)

2005年5月12日

3分钟阅读

viewsIcon

431308

downloadIcon

6686

一篇关于 ASP.NET DataGrid 多列下拉列表的文章。

显示将控件添加到 EditItemTemplate 时的图片。

引言

基于我之前开发的“ASP.NET 多列下拉列表”控件,我收到了许多电子邮件,要求将相同的控件用于 Web 应用程序的 DataGrid。现在,这个控件可以像普通的 MS DropDownList 一样用在 DataGrid 中,也可以作为常规下拉列表使用。它拥有所有常用的属性,如 DataTextFieldDataValueFieldDataSourceSelectedIndex 等。下载文件中包含 VB.NET 和 C# 的示例。在此示例中,我使用了 SQL Server 的 Northwind 数据库。

构建控件

构建此控件使用了以下 Web 服务器控件:

  1. 文本框
  2. Label
  3. Panel

将控件添加到 DataGrid

可以通过属性生成器将此控件添加到 DataGridItemTemplateEditItemTemplate 中。

  1. 将一个 DataGrid 拖到您的 Webform 上。
  2. 右键单击 DataGrid,选择“属性生成器”,然后选择“列”。
  3. 可以包含一个绑定列,也可以不包含,我已展示了两者的示例。
  4. 添加两个绑定列,设置标题和文本字段:SupplierID 和 CompanyName。
  5. 添加一个模板列,并将其标题设置为 Products。
  6. 取消选中“运行时自动创建列”复选框。
  7. 点击“确定”。
  8. 现在,右键单击 DataGrid 并选择“编辑模板”,您可以将其添加到 ItemTemplateEditItemTemplate 中。
  9. 设置控件的属性,例如 CssClassGridRowcolorDataTextfield 等。
  10. 关闭模板框。

注意事项

DataValueField 属性是 只读 的,这意味着您无法设置值。因此,请确保在您的查询中,行值字段始终是第一列,该列不会在下拉列表中显示。DataTextField 返回一个整数值,因此在设置此属性时,请输入您 "SELECT" 语句中需要显示在文本框中的列的位置。(例如,要在文本框中显示第二列“LastName”,请将 DataValueField 设置为 2。)如果您的 DataGrid 位于 "Table/Div/Span" 中,请确保“Style”属性中的“Position”属性设置为 absolute;如果未用于任何这些标签,则设置 DataGridStyle 属性。

请确保您的 DataGridItemStyleHorizontalAlignVerticalAlign 属性已按所示设置,否则控件可能无法在 DataGrid 中正确放置。例如:

<ItemStyle HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>

请参见下面的代码。例如,要使用 FirstNameLastName 填充下拉列表:

SELECT Employeeid,Firstname,LastName
From Employees

现在,如果添加到 EditItemTemplate 中(根据您的需求,绑定列可能需要也可能不需要),在我的示例中,我使用了两个 <BoundColumn>

<ASP:DATAGRID id="jskDataGrid" runat="server" 
    Font-Size="8pt" HeaderStyle-ForeColor="Tan" 
    AutoGenerateColumns="False" HeaderStyle-BackColor="Maroon" 
    HeaderStyle-Font-Bold="True" Font-Name="Verdana" ShowFooter="false" 
    BorderColor="Tan" DataKeyField="SupplierID" 
    OnUpdateCommand="MyDataGrid_Update" OnCancelCommand="MyDataGrid_Cancel" 
    OnEditCommand="MyDataGrid_Edit" CellSpacing="0" CellPadding="3" 
    Width="800" Style="Position:absolute;Top:0px;Left:0px">

  <HeaderStyle Font-Bold="True" ForeColor="Tan" BackColor="Maroon"></HeaderStyle>
  <Columns>
        <asp:EditCommandColumn ButtonType="LinkButton" 
             UpdateText="Update" CancelText="Cancel" EditText="Edit">
          <ItemStyle VerticalAlign="Top"></ItemStyle>
        </asp:EditCommandColumn>
        <asp:BoundColumn DataField="SupplierID" 
              ReadOnly="True" HeaderText="Supplier ID">
          <ItemStyle Wrap="False" VerticalAlign="Top"></ItemStyle>
        </asp:BoundColumn>
        <asp:BoundColumn DataField="CompanyName" 
              ReadOnly="True" HeaderText="Company Name">
          <ItemStyle Wrap="False" VerticalAlign="Top"></ItemStyle>
        </asp:BoundColumn>
        <asp:TemplateColumn HeaderText="Products">
    <ItemStyle HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
        <!-- Set these two properties as shown-->
        <%# DataBinder.Eval(Container.DataItem, "ProductName") %>
          </ItemTemplate>
          <EditItemTemplate>
            <TABLE cellSpacing="0" cellPadding="0" width="100%" border="0">
              <TR>
                <TD>
                  <jsk:mcDDList id="McDDList1" 
                    Width="200" 
                    SelectedIndex='<%# DataBinder.Eval(Container.DataItem, 
                                                          "ProductID") %>' 
                    cssClass="cStyle" Runat="server" 
                    DataSource="<%# PopulateDDList()%>"
                    DataTextField="2">
                  </jsk:mcDDList>
                </TD>
              </TR>
            </TABLE>
          </EditItemTemplate>
        </asp:TemplateColumn>
      </Columns>
</ASP:DATAGRID>

如果您想显示现有值,请添加“SelectedIndex”属性。

属性

  • DataTextField - 显示在控件中的字段。
  • DataValueField - 只读属性(用于标识行的值字段 - 默认是第一列 {0})。
  • DataSource - 用于填充下拉列表的数据集。
  • DDTextboxReadonly - 如果为 false,则可以输入自己的文本。
  • GridRowColor - 鼠标移动时更改行颜色。
  • GridTextColor - 鼠标移动时更改文本颜色。
  • ListBoxHeight - 设置下拉列表的高度。
  • ReturnsValue - 要获取文本,请将其设置为 false。更新时要获取值,请将其设置为 true
  • SelectedIndex - 如果设置,将在下拉列表中显示现有值。

填充 DataGrid

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    if (! IsPostBack)
    {
        BindDataGrid();
    }
}

protected void BindDataGrid()
{
    string sqlStr = "SELECT S.CompanyName, S.SupplierID," +
                    " P.ProductName, P.ProductID " +
                    "from Suppliers S inner join Products P " +
                    "on S.SupplierID = P.SupplierID ";
    sqlDa = new SqlDataAdapter(sqlStr, SqlCon);
    ds = new DataSet();
    sqlDa.Fill(ds, "Prod");
    jskDataGrid.DataSource = ds.Tables["Prod"];
    jskDataGrid.DataBind();
}

填充 DropDownList

public DataSet PopulateDDList()
{
    string sqlString = " select ProductID, ProductName, " +
                       "CategoryName as Name,UnitPrice as Price " +
                       "from Products p inner join Categories c " +
                       "on p.categoryid = c.categoryid ";
    SqlDataAdapter ad = new SqlDataAdapter(sqlString,SqlCon);
    DataSet ds = new DataSet();
    ad.Fill(ds,"Categories");
    return ds;
}

编辑/更新/取消的代码

protected void jskDataGrid_Edit(object sender, DataGridCommandEventArgs e)
{
    jskDataGrid.EditItemIndex = e.Item.ItemIndex;
    BindDataGrid();
}

protected void jskDataGrid_Cancel(object sender, DataGridCommandEventArgs e)
{
    jskDataGrid.EditItemIndex = -1;
    BindDataGrid();
}

protected void jskDataGrid_Update(object sender, DataGridCommandEventArgs e)
{
    try
    {
        string itemValue;
        string itemText;

        // To get the DataValueField of the DropDown
        ((ddList.mcDDList)e.Item.FindControl("McDDList1")).ReturnsValue = true;
        itemValue =
          ((ddList.mcDDList)e.Item.FindControl("McDDList1")).Text.ToString();

        // To get the DataTextField of the Dropdown
        ((ddList.mcDDList)e.Item.FindControl("McDDList1")).ReturnsValue = false;
        itemText =
          ((ddList.mcDDList)e.Item.FindControl("McDDList1")).Text.ToString();

        //write your update query
        //update table set col1 = itemtext where col2 = itemvalue
        //Execute the Query

        jskDataGrid.EditItemIndex = -1;
        BindDataGrid();
    }
    catch(Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        /*Close your Connection */
    }
}

关注点

该控件主要使用 JavaScript 构建。有一个名为“DDTextboxReadonly”的属性,该属性用于启用/禁用文本框,即您可以从列表中选择文本,也可以输入文本。

使用 Intellisense

在我之前的 文章 中,我展示了如何使用 Intellisense。zip 文件包含 .xsd 文件,请将其复制到以下位置:

  • C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\Packages\schemas\xml

并在您的 aspx 页面的 <body> 标签中添加以下代码:

<body MS_POSITIONING="GridLayout"
  xmlns:jsk="urn:http://schemas.ksjControls.com/DGDD/ASPNET">

历史

  • 版本 (1.0) - 初始版本 (发布于 2005 年 5 月 12 日)
  • 版本 (1.1) - 添加了新属性 ListBoxHeight 来调整下拉列表的高度。
  • 版本 (1.2) - 控件不会扩展 DataGrid 的行。
© . All rights reserved.