一个简单的例子说明GridView与DropDownList结合的用法。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowSorting="True" PageSize="6">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="UserID" HeaderText="用户ID" ReadOnly="True" />
<asp:BoundField DataField="User_Nm" HeaderText="用户姓名"/>
<asp:TemplateField HeaderText="员工性别">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlBind() %>'
DataValueField="User_Sex" DataTextField="User_Sex">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="User_Address" HeaderText="家庭住址" />
</Columns>
<RowStyle ForeColor="#008066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GridView_DropDownList : System.Web.UI.Page
{
SqlConnection sqlcon;
string strCon = "Data Source=.\\SQL2005;DataBase=Users;Uid=sa;Pwd=123";
protected void Page_Load(object sender, EventArgs e)
{
//DataTextFiled 获取或设置为列表项提供文本内容的数据源字段
//DataValueField获取或设置为各列表项提供值的数据源字段
if (!IsPostBack)
{
DropDownList ddl;
string sqlstr = "SELECT * FROM Users";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "AlLUser");
GridView1.DataSource = myds;
GridView1.DataBind();
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv = myds.Tables["ALLUser"].DefaultView[i];
if (Convert.ToString(mydrv["User_Sex"]).Trim() == "男")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 0;
ddl.SelectedItem.Text = "男";
}
else if (Convert.ToString(mydrv["User_Sex"]).Trim() == "女")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 1;
ddl.SelectedItem .Text = "女";
}
}
sqlcon.Close();
}
}
public SqlDataReader ddlBind()
{
string sqlstr = "SELECT DISTINCT User_Sex FROM Users";
sqlcon = new SqlConnection(strCon);
SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
sqlcon.Open();
return sqlcom.ExecuteReader();
}
}