<asp:TemplateColumn HeaderText="test">
<ItemTemplate>
<asp:DropDownList id="ddlTest" CssClass="button" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>要关联数据库在DataGrid的ItemDataBound里面处理
if (e.Item.FindControl("ddlTest")!=null)
{
DropDownList ddlPayMethod=(DropDownList)e.Item.FindControl("ddlTest");
//作绑定操作
}

解决方案 »

  1.   

    动态给DataGrid添加模板列
    难!   顶!
      

  2.   

    的html代码、控件以及用于在某个特定区域呈现控件的脚本。例如,一个Repeater控件有一个HeaderTemplate属性,它定义了repeaper控件的头部内容。通常你会运用asp.net的语法定义一个模板。例如下面的代码说明了怎样指定模板以画出Repeater的头和每一行的内容。 
    <asp:repeater runat="server">
      <HeaderTemplate>
        <h2>Employees</h2>
        <table border="0">
      </HeaderTemplate>  <ItemTemplate>
        <tr>...</tr>
      </ItemTemplate>
    </asp:repeater>
    当它开始呈现Repeater控件的内容时,ASP.NET用在模板中定义的内容和进程一起绑定数据,创建描述数据的html代码。所有的服务器控件都包含一个可以用html描述并呈现它们自己的模板。
    .NET Framework框架运用ITemplate接口在运行时处理模板中的每层控件,这些控件能够绑定到数据然后呈现为该模板的一部分。如果你仅运用inline tags在aspx页面中声明了一个公共样式的模板,你不必了解ITemplate 接口。只有当你需要更进一步的了解和研究怎样创建模板和动态的用程序声明模板时, 充分的理解ITemplate 接口就很重要了。但是在我们了解它之前,让我们一起来看一下模板在datagrid控件中的应用。  DataGrid的模板列
    基于模板的列在datagrid控件中扮演了一个很重要的角色,它们允许你增加任意一种类型的列到datagrid,datagrid通过纯文本的形式或者某种预定义的列类型显示内容。然而,有时预定义的列类型并不能实现我们想要的东西。模板列有四种不同的模板,如图1
    Figure 1 DataGrid Column Templates 
    Name Description
    ItemTemplate Contains the template for the items in a DataGrid's column. 
    <ItemTemplate>
      <asp:label runat="server" text= '<%# ... %>'...>
    </ItemTemplate>
    You can use any combination of HTML text and ASP.NET controls to populate the column.
    EditItemTemplate Controls the contents of the item selected for editing in the column of the DataGrid control. Place the controls you need for editing the cell between the opening and closing EditItemTemplate tags. 
    <EditItemTemplate>
      <asp:textbox runat="server" text= '<%# ... %>'...>
    </EditItemTemplate>
    HeaderTemplate Contains the template for the heading section. 
    <HeaderTemplate>
      <asp:label runat="server" text= "Header"...>
    </HeaderTemplate>
    If you omit this template, the column header is rendered with a label or a hyperlink if sorting is enabled. By specifying a custom template, you make yourself responsible to provide the user interface needed to enable sorting on the column.
    FooterTemplate Contains the template for the footer section of the column. The default value is a null reference. 
    <FooterTemplate>
      <asp:label runat="server" text= "..."...>
    </FooterTemplate>
    The footer is displayed only if the ShowFooter property of the DataGrid is set to True.你可能会频繁的使用模板列(ItemTemplate)。它定义了怎么样显示列中的单元格及由哪些元素组成控件的内容。HeaderTemplate 和 FooterTemplate我们就不说了,相信大家都知道是干什么用的。当列的所属行进入编辑模式时,EditItemTemplate属性指明单元格应该怎样变化。但要注意的是,它和datalist控件不一样,datagrid没有选中模板。
    当你需要用不规范的方式显示整个列的时候,你的DataGrid应该用基于模板的列。如果你需要显示数据的数据无法用datagrid 提供的普通的模板显示时,这时,模板就是你的最佳选择了。下面的代码演示了怎样绑定数据到datagrid控件的模板列。  
       <asp:TemplateColumn runat="server" 
       HeaderText="heading">        
         <itemtemplate>
           ...ASP.NET layout goes here...
         </itemtemplate>
       </asp:TemplateColumn>
    注意模板列和其它类型的列一样,也有一个可用于排序的标题文字。模板列没有直接用于绑定数据源字段的属性。也就是在TemplateColumn类的成员里面,你找不到任何DataField或DataTextField属性。
    缺少直接绑定数据源字段的属性是为了更灵活的处理列的显示布局。要呈现一个列,你可以用label控件的text属性,当然也可以用dropdownlist控件或者image控件,这两个控件都没有类似text的属性。结果一样,你都必须用一个数据绑定表达式来绑定数据。在我看来,虽然要写冗长的数据绑定表达式,但它却给了你极大的灵活性。
     下面的代码片断演示怎样正确绑定内容到item template:
       <asp:label runat="server" 
         Text='<%# DataBinder.Eval(Container.DataItem, 
              "lastname") %>' 
       />        
    通过用DataBinder.Eval方法,你能够访问当前数据源的任何一个字段。除此以外,你还可以结合任何的排序表达式来对字段进行排序。这是用其它简单的模板列无法实现的。 
    Figure 2 Column在图2中,你能看到一个基于模板列实现的例子,它演示了怎样在一列中显示数据源中两个字段。在不是基于模板的列中只能获得(显示)一个字段。这个模板的代码如下所示:
    <itemtemplate>
    <%#
      "<b>" + 
      DataBinder.Eval(Container.DataItem, "lastname") +
      "</b>, " + 
      DataBinder.Eval(Container.DataItem, "firstname") 
    %>
    </itemtemplate>
      

  3.   

    模板列的头
    既然TemplateColumn类给了HeaderTemplate(FooterTemplate)属性,你就可以定制给定列的头(header)和尾(footer)。说到定制,它在这里是非常重要的一点。因为在普通的数据绑定列中没有header模板和footer模板。HeaderTemplat只能应用在TemplateColumn 类的一个实例中。对于这个实例,如果你想用一个非标准的方法编辑该列的内容(例如说你想添加对内容的验证),你可以用headertemplate,也可以用一个简单的BoundColumn类来呈现。
    真的可以改变列的header布局吗?如果你需要根据某个表达式对列进行排序,排序机制是datagrid自动在列的头部插入一个hyperlink控件,当用户单击hyperlink控件时,asp.net会根据hyperlink控件的href属性触发一个回发事件,从而对该列进行排序操作。就算你不需要排序你也可以很自由的更改列的header。如果你需要用ItemCreated事件在header中增加其它的控件及脱离datagrid控件做其它的任何事情。下面请看一个例子:
    Figure 3 Adding the Sort Dropdown 
    public void ItemCreated(Object sender, DataGridItemEventArgs e)
    {
        ListItemType lit = e.Item.ItemType;
        if (lit == ListItemType.Header)
        {
            // Create and fill a dropdown list control
            DropDownList dd = new DropDownList();
            dd.ID = "ddSort";
            ListItem li1, li2, li3;        // ListItem constructor takes Text and Value for the item
            li1 = new ListItem("Title of courtesy", "titleofcourtesy");
            dd.Items.Add(li1);        li2 = new ListItem("Last Name", "lastname");
            dd.Items.Add(li2);        li3 = new ListItem("First Name", "firstname");
            dd.Items.Add(li3);        // Selects the item, if any, that was selected last time
            dd.SelectedIndex = Convert.ToInt32(grid.Attributes["FieldIndex"]);        // Add the dropdown list to the header of the 2nd column
            TableCell cell = (TableCell) e.Item.Controls[1];
            cell.Controls.Add(dd);
        }
    }public void SortCommand(Object sender, DataGridSortCommandEventArgs e)
    {
        // Code that retrieves the grid's data source GOES HERE
        &#8226;&#8226;&#8226;    // Sort by the specified expression or figure it out 
        if (e.SortExpression != "*")
            dv.Sort = e.SortExpression;
        else
        {
            // Retrieves the dropdown list control through its ID 
            DataGridItem dgi = (DataGridItem) e.CommandSource;
            DropDownList dd = (DropDownList) dgi.FindControl("ddSort");        // Retrieves the sorting expression from the list
            dv.Sort = dd.SelectedItem.Value;         // Persists the currently selected dropdown item
            grid.Attributes["FieldIndex"] = dd.SelectedIndex.ToString();
        }
        
        // Refreshes the grid
        grid.DataBind();
    }
      

  4.   

    你在服务端动态生成DataGrid后,再用Response.write输入模板列的HTML代码看看行不行?我没有试用。你能说一下,你为什么要用这种算法吗?
      

  5.   

    你在服务端动态生成DataGrid后,再用Response.write输入模板列的HTML代码看看行不行?我没有试用。你能说一下,你为什么要用这种算法吗?
      

  6.   

    你在服务端动态生成DataGrid后,再用Response.write输入模板列的HTML代码看看行不行?我没有试用。你能说一下,你为什么要用这种算法吗?
      

  7.   

    一定要是模板列吗?不能在某列中直接加DropDownList控件吗?在ItemDataBound动态定义DropDownList并添加到你要添加的列中DropDownList中的item当然也可以动态添加了
      

  8.   

    to tonghaibinfc(在哪都是外地人) :
    如何操作,具体说说。
      

  9.   

    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="ComboInGrid.aspx.vb" Inherits="code.ComboInGrid"%>
    <%@ Register TagPrefix="uc1" TagName="connection" Src="../connection.ascx" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <title>ComboInGrid</title>
    <script language="JavaScript" type="text/JavaScript">
    function getconfirm() 

    if (confirm("确定要删除此记录吗?")==true) 
    return true; 
    else 
    return false; 
    }
    </script>
    <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
    <uc1:connection id="Connection1" runat="server"></uc1:connection>
    <DIV id="DIV1" style="DISPLAY: inline; Z-INDEX: 102; LEFT: 824px; WIDTH: 104px; POSITION: absolute; TOP: 32px; HEIGHT: 40px" runat="server" ms_positioning="FlowLayout">Label</DIV>
    <asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" Width="648px" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4" ShowFooter="True" PageSize="5" Height="300px">
    <SelectedItemStyle Font-Bold="True" ForeColor="#663399" BackColor="#FFCC66"></SelectedItemStyle>
    <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
    <FooterStyle ForeColor="#330099" BackColor="#FFFFCC"></FooterStyle>
    <Columns>
    <asp:TemplateColumn HeaderText="员工编号">
    <ItemTemplate>
    <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.employeeid") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:LinkButton id="insert" runat="server" CommandName="insert">新增</asp:LinkButton>
    </FooterTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="姓">
    <ItemTemplate>
    <asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.firstname") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
    </FooterTemplate>
    <EditItemTemplate>
    <asp:TextBox id=TextBox2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.firstname") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="名">
    <ItemTemplate>
    <asp:Label id=Label4 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.lastname") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:TextBox id="TextBox3" runat="server"></asp:TextBox>
    </FooterTemplate>
    <EditItemTemplate>
    <asp:TextBox id=TextBox4 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.lastname") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="城市">
    <ItemTemplate>
    <asp:Label id=Label2 runat="server" Text='<%# databinder.eval(container.dataitem,"city") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:DropDownList id=DropDownList2 runat="server" Width="96px" DataMember="cities" DataValueField="city" DataTextField="city" DataSource="<%# ds %>">
    </asp:DropDownList>
    </FooterTemplate>
    <EditItemTemplate>
    <FONT face="宋体">
    <asp:DropDownList id=Dropdownlist1 runat="server" Width="96px" SelectedIndex='<%# city_index(databinder.eval(container.dataitem,"city")) %>' DataMember="cities" DataValueField="city" DataTextField="city" DataSource="<%# ds %>">
    </asp:DropDownList></FONT>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
    <asp:ButtonColumn Text="删除" CommandName="Delete"></asp:ButtonColumn>
    </Columns>
    <PagerStyle HorizontalAlign="Center" ForeColor="#330099" BackColor="#FFFFCC" Mode="NumericPages"></PagerStyle>
    </asp:DataGrid>
    </form>
    </body>
    </HTML>
      

  10.   

    接Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Public Class ComboInGrid
        Inherits System.Web.UI.Page
        Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
        Protected WithEvents DIV1 As System.Web.UI.HtmlControls.HtmlGenericControl
        Protected connection1 As connection
    #Region " Web 窗体设计器生成的代码 "    '该调用是 Web 窗体设计器所必需的。
        <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: 此方法调用是 Web 窗体设计器所必需的
            '不要使用代码编辑器修改它。
            InitializeComponent()
        End Sub#End Region    Public ds As New DataSet() '摸板列调用申明为全局
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            '在此处放置初始化页的用户代码
            If Not Page.IsPostBack Then
                bindgrid()
            End If
        End Sub    Function city_index(ByVal city As String) As Integer
            Dim cn As SqlConnection = New SqlConnection(connection1.connstr)
            Dim cmd As SqlCommand = New SqlCommand("select distinct city from employees", cn)
            Dim cityhash As New Hashtable()
            Dim dr As SqlDataReader, i As Integer = 0
            cn.Open()
            dr = cmd.ExecuteReader()        While dr.Read
                cityhash(dr("city")) = i
                i = i + 1
            End While
            cn.Close()
            Return cityhash(city)
        End Function
        Sub bindgrid()
            Dim conn As SqlConnection = New SqlConnection(connection1.connstr)        Dim adapter As SqlDataAdapter        adapter = New SqlDataAdapter("select employeeid,firstname,lastname,city from employees", conn)
            adapter.Fill(ds, "employees")        adapter = New SqlDataAdapter("select distinct city from employees", conn)
            adapter.Fill(ds, "cities")        With DataGrid1
                .DataSource = ds
                .DataMember = "employees"
                .DataKeyField = "employeeid"
                .DataBind()
            End With    End Sub
        Private Sub DataGrid1_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.EditCommand
            DataGrid1.EditItemIndex = e.Item.ItemIndex
            bindgrid()
        End Sub
        Private Sub DataGrid1_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.CancelCommand
            DataGrid1.EditItemIndex = -1
            bindgrid()
        End Sub    Private Sub DataGrid1_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.UpdateCommand
            Dim cn As SqlConnection = New SqlConnection(connection1.connstr)
            Dim cmd As SqlCommand = New SqlCommand()        Dim firstname As String, lastname As String, city As String
            Dim empid As Integer
            'empid = Integer.Parse(e.Item.Cells(0).Text)  '不采用主键方式直接取单元格的值
            empid = DataGrid1.DataKeys(e.Item.ItemIndex)
            firstname = "'" & CType(e.Item.Cells(1).Controls(1), TextBox).Text & "'"
            lastname = "'" & CType(e.Item.Cells(2).Controls(1), TextBox).Text & "'"   '如果不用模板列可用controls(0)之间取值,也可用e.item.findcontrol("textbox2")
            city = "'" & CType(e.Item.Cells(3).Controls(1), DropDownList).SelectedItem.Text & "'" '此模板列有两个控件        cn.Open()
            cmd.Connection = cn
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "update employees set firstname=" & firstname _
            & ",lastname=" & lastname & ",city=" & city & " where employeeid=" & empid        cmd.ExecuteNonQuery()        DataGrid1.EditItemIndex = -1
            bindgrid()    End Sub    Private Sub DataGrid1_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.DeleteCommand
            Dim cn As SqlConnection = New SqlConnection(connection1.connstr)
            Dim empid As Integer
            ' empid = Integer.Parse(e.Item.Cells(0).Text)
            empid = DataGrid1.DataKeys(e.Item.ItemIndex)
            Try
                'sqlcommand的另类执行方法
                Dim cmd As SqlCommand = New SqlCommand("delete from employees where employeeid=" & empid, cn)
                cn.Open()
                cmd.ExecuteNonQuery()
            Catch er As SqlException            Response.Write(er.Errors)
                Response.Write(er.Message)
                Response.Write(er.Number.ToString)        End Try
            cn.Close()
            bindgrid()
        End Sub    Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                Dim i As LinkButton
                i = CType(e.Item.Cells(5).Controls(0), LinkButton)
                i.Attributes.Add("onclick", "return getconfirm();")
            End If
        End Sub    Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
            If e.CommandName = "insert" Then
                Dim ft As TextBox = e.Item.FindControl("textbox1")
                Dim lt As TextBox = e.Item.FindControl("textbox3")
                Dim cdrop As DropDownList = e.Item.FindControl("dropdownlist2")            Dim firstname As String, lastname As String, city As String
                firstname = "'" & ft.Text & "'"
                lastname = "'" & lt.Text & "'"
                city = "'" & cdrop.SelectedItem.Text & "'"            Dim cn As New SqlConnection(connection1.connstr)
                Dim cmdstring = "insert into employees(firstname,lastname,city) values(" & _
                firstname & "," & lastname & "," & city & ")"
                DIV1.InnerHtml = cmdstring
                Try
                    Dim cmd As New SqlCommand(cmdstring, cn)
                    cn.Open()
                    cmd.ExecuteNonQuery()            Catch err As SqlException
                    DIV1.InnerHtml = err.Message
                End Try
                cn.Close()
                bindgrid()
            End If
        End Sub
    End Class
      

  11.   

    呵呵,看我的吧:在your DataGrid添加onItemDataBound="ItemDataBound"
    然后: your *.aspx.cs:
    /// <summary>
    /// 控制网格显示风格
    /// </summary>
    public void ItemDataBound(Object sender, DataGridItemEventArgs e)
    {
    int intCellCount=e.Item.Cells.Count;
    DataRowView drv = (DataRowView) e.Item.DataItem;
    if (drv == null) return;
    //序号
    if (drv["序号"]!=null)
    {
    e.Item.Cells[0].Attributes["Width"]="30px";
    e.Item.Cells[0].Attributes["Height"]="18px";
    }

    //数据类型
    if (drv["数据类型"]!=null)
    {
    TableCell tc = e.Item.Cells[7];
    tc.Attributes["Width"]="50px";
    string _sql="SELECT DISTINCT a.coldatatype "+
    "FROM sys_FlexHeadCtl as a "+
    "WHERE (((a.coldatatype)<>'')) "+
    "ORDER BY a.coldatatype";
    if(oleCn.State!=ConnectionState.Open)
    {
    oleCn.ConnectionString=strSqlCon;
    oleCn.Open();
    }
    DataSet ds = new DataSet();
    OleDbDataAdapter oleDa=new OleDbDataAdapter();
    oleCmd.Connection=oleCn;
    oleCmd.CommandText=_sql;
    oleCmd.CommandType=CommandType.Text;
    oleDa.SelectCommand=oleCmd;
    oleDa.Fill(ds,"myDDL");
    DropDownList ddl=new DropDownList();
    ddl.BorderStyle=BorderStyle.None;
    ddl.DataTextField="coldatatype";
    //ddl.DataValueField="coldatatype"; 
    ddl.Style.Add("BACKGROUND-COLOR","transparent");
    ddl.DataSource=ds.Tables[0];
    ddl.DataBind();
    tc.Controls.Add(ddl);
    ListItem li=new ListItem("","");
    ddl.Items.Insert(0,li);
    if((drv["数据类型"]).ToString()!="")
    ddl.SelectedIndex=ddl.Items.IndexOf(ddl.Items.FindByText((drv["数据类型"]).ToString()));
    else
    ddl.SelectedIndex=0;
    }
    e.Item.Attributes["id"]=
    e.Item.ItemType.ToString()+e.Item.ItemIndex.ToString();
    }
      

  12.   

    <%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.SqlClient" %>
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <script language="C#" runat="server">
        private void Page_Load(Object sender, EventArgs E) 
        {
                    MyDataGrid.DataSource = GetDataTable(); 
    EditCommandColumn ec = new EditCommandColumn();
    ec.ItemStyle.Width=(Unit)0.20;
    ec.EditText="编辑";
    ec.ButtonType=ButtonColumnType.LinkButton;
    ec.ItemStyle.VerticalAlign=VerticalAlign.Middle;
    ec.ItemStyle.HorizontalAlign=HorizontalAlign.Left;
    ec.ItemStyle.Wrap = false;
    ec.CancelText="Cancel";
                    ec.UpdateText="Update" ;
                    ec.HeaderText="Edit item";
    MyDataGrid.EditCommand+=new DataGridCommandEventHandler(MyDataGrid_Edit);
    MyDataGrid.CancelCommand+=new DataGridCommandEventHandler(MyDataGrid_Cancel);
    MyDataGrid.UpdateCommand+=new DataGridCommandEventHandler(MyDataGrid_Update);
    MyDataGrid.Columns.Add(ec); ButtonColumn btc = new ButtonColumn();
    btc.ItemStyle.Width=(Unit)0.20;
    btc.Text="删除";
    btc.ItemStyle.VerticalAlign=VerticalAlign.Middle;
    btc.ItemStyle.HorizontalAlign=HorizontalAlign.Left;
    btc.ItemStyle.Wrap = false;
    MyDataGrid.Columns.Add(btc);
                    MyDataGrid.DataBind(); 
    if(!IsPostBack){
    BindGrid();
    }
        }
    void BindGrid(){
            MyDataGrid.DataSource = GetDataTable(); 
    MyDataGrid.Columns.Add(DynamicColumns("au_id",false));
    MyDataGrid.Columns.Add(DynamicColumns("au_lname",true));
    MyDataGrid.AutoGenerateColumns=false;
    MyDataGrid.DataKeyField = "au_id";
    MyDataGrid.ItemDataBound+=new DataGridItemEventHandler(MyDataGrid_OnItemDataBound);
            MyDataGrid.DataBind(); 
     }
    public TemplateColumn DynamicColumns(string column, bool isEditable)
    {
    TemplateColumn genericcolumn = new TemplateColumn();
    genericcolumn.HeaderText = column;
    genericcolumn.ItemTemplate = new DataGridTemplate(ListItemType.Item,column);
    if(isEditable)
    {
    genericcolumn.EditItemTemplate = new DataGridTemplate(ListItemType.EditItem,column);
    }
    return genericcolumn;
    }
    public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E) {     MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
    BindGrid();
    label1.Text=MyDataGrid.EditItemIndex.ToString()+"<br>"+MyDataGrid.Columns.Count.ToString()+"<br>";
    }
    public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
    {
    MyDataGrid.EditItemIndex = -1;
    BindGrid();
    }
    public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
    {
    string uid = E.Item.UniqueID + ":";
    string au_id = (string)MyDataGrid.DataKeys[E.Item.ItemIndex];
    string lname = (Request.Form[uid+"au_lname"].ToString());
    label2.Text = au_id;
    label3.Text = lname;
    MyDataGrid.EditItemIndex = -1;
    BindGrid();
    }
        public void MyDataGrid_OnItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
    if(e.Item.ItemType == ListItemType.EditItem)
    {
    DropDownList DropList= (DropDownList)e.Item.FindControl("au_lname");
        String myRole = DataBinder.Eval(e.Item.DataItem, "au_lname").ToString();
    DropList.Items.FindByText(myRole).Selected = true;
    }
    }
    public class DataGridTemplate : ITemplate
    {
    ListItemType templateType;
    string columnName1;
    public DataGridTemplate(ListItemType type, string colname1)
    {
    templateType = type;
    columnName1 = colname1;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
    Literal lc = new Literal();
    switch(templateType)
    {
    case ListItemType.Header:
    lc.Text = "<B>" + columnName1 + "</B>";
    container.Controls.Add(lc);
    break;
    case ListItemType.Item:
    container.Controls.Add(lc);
    lc.DataBinding += new EventHandler(TemplateControl_DataBinding);
    lc.ID = columnName1;
    break;
    case ListItemType.EditItem:
    DropDownList DropList = new DropDownList();
    DropList.ID = columnName1;
    container.Controls.Add(DropList);
          ArrayList values = new ArrayList();
        values.Add ("Doe");
        values.Add ("White");
        values.Add ("Green");
        values.Add ("Carson");
        values.Add ("O'Leary");
        values.Add ("Straight");
        values.Add ("Bennet");
        values.Add ("Dull");
        values.Add ("Gringlesby");
        values.Add ("Locksley");
        values.Add ("Yokomoto");
        values.Add ("Stringer");
        values.Add ("MacFeather");
        values.Add ("Karsen");
        values.Add ("Hunter");
        values.Add ("McBadden");
        DropList.DataSource = values;
        DropList.DataBind();
    break;
    case ListItemType.Footer:
    lc.Text = "<I>" + columnName1 + "</I>";
    container.Controls.Add(lc);
    break;
    }
    }
    public void TemplateControl_DataBinding(object sender, System.EventArgs e)
    {
    Literal lc;
    lc = (Literal) sender;
    DataGridItem container = (DataGridItem) lc.NamingContainer;
    lc.Text += ((DataRowView)container.DataItem)[columnName1].ToString()+"<br>";
    }
         }
    public DataTable GetDataTable()
    {
    String selectCmd = "select * from Authors where state = 'CA'";
    SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;database=pubs;Integrated Security=SSPI");
    SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
    DataSet ds = new DataSet();
    myCommand.Fill(ds, "Authors");
    DataTable dt = ds.Tables["Authors"];
    return dt;
    }
    </script>
    <body style="font: 10pt verdana">
      <form runat="server">
        <h3><font face="Verdana">Parameterized Select to a DataGrid Control</font></h3>
        <ASP:DataGrid id="MyDataGrid" runat="server"
          Width="700"
          BackColor="#ccccff" 
          BorderColor="black"
          ShowFooter="false" 
          CellPadding=3 
          CellSpacing="0"
          Font-Name="Verdana"
          Font-Size="8pt"
          HeaderStyle-BackColor="#aaaadd"
      AutoGenerateColumns="false"
         >
    </ASP:DataGrid>
    <asp:label ID="label1" runat="server"></asp:label><br>
    <asp:label ID="label2" runat="server"></asp:label><br>
    <asp:label ID="label3" runat="server"></asp:label><br>
    </form>
    </body>
    </html>
    效果如:
    http://218.84.107.5/g.aspx