datagrid与DropDownList关联使用

时间:2021-09-22 09:46:34

     最近做一个页面需要用到这个两个控件,之前虽然看过,但是没有动手实践过。突然要做这么一个页面,并用上,真的有点着急。于是乎,网上疯狂找datagrid与DropDownList 的例子,找了很多很多,看了,并实践了,但是不是我想要的效果。昨天晚上琢磨了好几个小时,都没有弄好,后来干脆不弄了,躺在床上想了又想,结合网上找的案例,应该是灵感突现,今天一来到公司就动手实践。实践是检验最好的标准。实现了,成功了。

    很高兴,急着把它写成笔记,一来记录,二来分享吧。开始贴码。

    一、页面代码

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="datagridyuDropDownList.aspx.vb" Inherits="firstwebVbTest.datagridyuDropDownList" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    .dghotelRange
{
     min-width:900px;
     width:auto;
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:DataGrid ID="dgtest" runat="server" AutoGenerateColumns="False"
                 CssClass="dghotelRange">
                <AlternatingItemStyle BackColor="#E0E0E0"></AlternatingItemStyle>
                <HeaderStyle Font-Bold="True" ForeColor="#E7E7FF" BackColor="#4A3C8C"></HeaderStyle>
                <Columns>
                <asp:TemplateColumn HeaderText="编号"> 
                    <ItemTemplate> 
                      <asp:Literal    ID="labId" runat="server" Text='<%# Container.DataItem("Id") %>'></asp:Literal>
                    </ItemTemplate>
                    </asp:TemplateColumn>
                   <asp:BoundColumn DataField="Name" HeaderText="名字"></asp:BoundColumn>
                    <asp:TemplateColumn HeaderText="父编号"> 
                    <ItemTemplate> 
                     <asp:textbox id="txtparenetId" runat="server" Text='<%# Container.DataItem("parenetId") %>' width="50px"></asp:textbox>
                    </ItemTemplate>
                    </asp:TemplateColumn>
                     <asp:TemplateColumn HeaderText="类别"> 
                    <ItemTemplate> 
                      <asp:DropDownList ID="ddlUsers" runat="server" ></asp:DropDownList> 
                    </ItemTemplate>
                    </asp:TemplateColumn>
                     <asp:BoundColumn DataField="memo" HeaderText="备注"></asp:BoundColumn>
                </Columns>
            <PagerStyle Mode="NumericPages"></PagerStyle>
     </asp:DataGrid>
        <asp:Button ID="btnGet" runat="server" Text="显示" />
    </div>
    </form>
</body>
</html>

二、后台代码

连接数据库的代码有点丑陋了。

Imports System.Data
Imports System.Data.SqlClient
Public Class datagridyuDropDownList
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
    Dim str As String = "Data Source=xxxxx;Initial Catalog=Mytest;Integrated Security=True"
    Dim conn As SqlConnection = New SqlConnection(str)
    Dim cmd As SqlCommand = New SqlCommand()
    Dim ad As SqlDataAdapter = New SqlDataAdapter()
    ''' <summary>
    ''' DataGrid 绑定数据下拉列表绑定数据显示---关联的(另一个表的text值)
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub getDataTable()
        Dim ds As DataSet = New DataSet()
        Dim strsql = "select   top 10 Id, Name, parenetId, memo from test"
        Try
            conn.Open()
            cmd.CommandText = strsql
            cmd.Connection = conn
            ad.SelectCommand = cmd
            ad.Fill(ds)
            dgtest.DataSource = ds.Tables(0).DefaultView
            dgtest.DataBind()
            '这一段代码就是绑定下拉类别一出来的值 这个是关联的 实现这个花了很多时间
            For i As Integer = 0 To dgtest.Items.Count - 1
                Dim NID As Literal = dgtest.Items.Item(i).FindControl("labId")
                Dim Users As DropDownList = dgtest.Items.Item(i).FindControl("ddlUsers")
                GetDataUser(Users)
                Users.SelectedValue = NID.Text
            Next

        Catch ex As Exception

        Finally
            cmd.Dispose()
            ad.Dispose()
            conn.Close()
        End Try
       
    End Sub
    ''' <summary>
    ''' 初始时绑定数据
    ''' </summary>
    ''' <param name="ddlUsers"></param>
    ''' <remarks></remarks>
    Public Sub GetDataUser(ByVal ddlUsers As DropDownList)
        Dim strsql = "select  top 10  Id, Names from Users"
        Dim ds As DataSet = New DataSet()
        conn.Close()
        Try
            conn.Open()
            cmd.CommandText = strsql
            cmd.Connection = conn
            ad.SelectCommand = cmd
            ad.Fill(ds)
            ddlUsers.DataSource = ds.Tables(0).DefaultView
            ddlUsers.DataTextField = "Names"
            ddlUsers.DataValueField = "Id"
            ddlUsers.DataBind()
        Catch ex As Exception

        Finally
            cmd.Dispose()
            ad.Dispose()
            conn.Close()

        End Try
    End Sub
    ''' <summary>
    ''' 下拉绑定数据 拥有更改时
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetUsersDataTable() As DataTable
        Dim strsql = "select  top 10  Id, Names from Users"
        Dim dt As DataTable = New DataTable()
        Dim ds As DataSet = New DataSet()
        Try
            conn.Open()
            cmd.CommandText = strsql
            cmd.Connection = conn
            ad.SelectCommand = cmd
            ad.Fill(ds)
            dt = ds.Tables(0)
        Catch ex As Exception

        Finally
            cmd.Dispose()
            ad.Dispose()
            conn.Close()
        End Try
        Return dt
    End Function
    ''' <summary>
    ''' 这个是参考更改下拉数据代码 只是我这里没有做修改和添加的代码 所以在这里没有用
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub dgtest_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgtest.ItemDataBound
        If e.Item.ItemType = ListItemType.EditItem Then
            Dim ddl As DropDownList = CType(e.Item.FindControl("ddlUsers"), DropDownList)
            ddl.DataSource = GetUsersDataTable()
            ddl.DataValueField = "Id"
            ddl.DataTextField = "Names"
            ddl.DataBind()
            Dim dv As DataRowView = CType(e.Item.DataItem, DataRowView)
            ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(dv("Names").ToString()))
        End If
    End Sub
    ''' <summary>
    ''' 显示数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub btnGet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGet.Click
        getDataTable()
    End Sub
End Class

三、显示的结果如下图

datagrid与DropDownList关联使用

总结

    付出,还是有收获的。

参考链接:

http://www.cnblogs.com/skylaugh/archive/2006/03/17/352333.html

http://wzoot.blog.163.com/blog/static/41638800200791643035837/