在asp.net 2.0中,在一個gridview里,可以嵌套進一個dropdownlist,這是十分容易的事情,而這里講的是,
在每個dropdownlist里,都綁定的是不同的內容,比如在northwind數據庫中,可以用GRIDVIEW顯示出
每個category類別,同時每一行的category類別里可以已dropdonwlist下拉框的形式,列出該分類下的所有
產品.下面介紹實現(xiàn)的方法
首先是頁面部分的代碼
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="Category Name" />
<asp:TemplateField HeaderText=" <ItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 在codebehind部分, // This is because Table[1] contains Categories GridView1.DataSource = GetDataSet().Tables[1]; GridView1.DataBind(); } string query = @"SELECT p.CategoryID,p.ProductID, p.ProductName FROM Products p SELECT c.CategoryID,c.CategoryName FROM Categories c"; string connectionString = "Server=localhost;Database=Northwind;user id=sa;passWord=123456"; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter(query, myConnection); DataSet ds = new DataSet(); ad.Fill(ds); return ds; } DataColumn productIDColumn = new DataColumn("ProductID"); DataColumn productNameColumn = new DataColumn("ProductName"); myTable.Columns.Add(productIDColumn); myTable.Columns.Add(productNameColumn); DataSet ds = new DataSet(); ds = GetDataSet(); int categoryID = 0; string expression = String.Empty; if (e.Row.RowType == DataControlRowType.DataRow) categoryID = Int32.Parse(e.Row.Cells[0].Text); expression = "CategoryID = " + categoryID; DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1"); DataRow[] rows = ds.Tables[0].Select(expression); foreach (DataRow row in rows) DataRow newRow = myTable.NewRow(); newRow["ProductID"] = row["ProductID"]; newRow["ProductName"] = row["ProductName"]; myTable.Rows.Add(newRow); } ddl.DataSource = myTable; ddl.DataTextField = "ProductName"; ddl.DataValueField = "ProductID"; ddl.DataBind(); } } expression = "CategoryID = " + categoryID;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
private DataSet GetDataSet()
{
在上面的代碼中,首先我們通過典型的dataset返回,綁定到gridview上去,注意這里sql語句里有兩句,第一句是返回產品,第二句是返回所有的類別category,而在綁定gridview時,我們用
GridView1.DataSource = GetDataSet().Tables[1];,將第一個table表里的category記錄綁定到gridview里去,接下來,我們要處理模版列中的dropdownlist了,這個可以在row_databound事件中寫入代碼,如下
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataTable myTable = new DataTable();
{
{
這里的原理大致如下:
首先,我們建立了一個datatable,包含了productid,productname列,然后將其與 gridview綁定,之后再用
categoryID = Int32.Parse(e.Row.Cells[0].Text);
構造一個篩選表達式,這里指定為categoryID,然后通過
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
DataRow[] rows = ds.Tables[0].Select(expression);
,找出符合其類別等于某一categoryID的所有產品,這里構造出datarow集合了,最后,使用循環(huán)
,將某類別下的產品全部添加到datatable中去,最后將datatable和dropdownlist綁定,就實現(xiàn)功能了
新聞熱點
疑難解答