[ASP.NET] GridView 裡實現連動下拉選單

  • 15136
  • 0
  • 2011-11-11

GridView 裡實現連動下拉選單

 以下範例可以實現在GridView裡,做到連動式下拉選單

一開始先在GridView裡二個Cell的Template裡放入DropDownList

 暫名為DropDownList1及DropDownList2

考量到效能問題,所以一開始先下一次SQL把DropDownList1所需要的item資料放到一個DataTable裡

 

 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowIndex > -1)
  {
     if (e.Row.FindControl("DropDownList1") != null)
     {
        DropDownList droplist1 = e.Row.FindControl("DropDownList1") as DropDownList;
        droplist1.DataSource = dt;  //dt為一個DataTable
        droplist1.DataTextField = "name";
        droplist1.DataValueField = "id";
        droplist1.DataBind();
      }

  }

}

接著在DropDownList1的SelectedIndexChanged事件去處理DropDownList2的item , 這裡有二種方式可以達成

分列如下

方法(1)

 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList DropDownList1 = ((DropDownList)sender);
   //方法1
   DropDownList DropDownList2 = DropDownList1.NamingContainer.FindControl("DropDownList2") as DropDownList;
   DropDownList2.Items.Clear();
   DropDownList2.Items.Add(new ListItem(DropDownList1.SelectedValue, DropDownList1.SelectedValue));
}

 

方法(2)

 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   DropDownList DropDownList1 = ((DropDownList)sender);
   //方法2
   DropDownList DropDownList2 = DropDownList1.Parent.FindControl("DropDownList2") as DropDownList;
   DropDownList2.Items.Clear();
   DropDownList2.Items.Add(new ListItem(DropDownList1.SelectedValue, DropDownList1.SelectedValue));
}

 

這樣就可以囉

是不是很簡單啊,不過就如一開始所說的,在考量效能上所以先採用DataTable的方法來放Data,而效能卻往往也是寫程式最容易忽略的

這樣的好處是在於接下來不用跑GriveView的RowDataBound事件裡多跑太多次SQL

DropDownList1的item利用GridView1_RowDataBound事件先Bind進來

 

若本文對您有所幫助,歡迎轉貼,但請在加註【轉貼】及來源出處,並在附上本篇的超連結,感恩您的配合囉。

By No.18