2011-12-19 75 views
1

假设我在GridView控件模板下拉列表(其中为界,所有行) 的下拉列表是通过一个数组充满..的GridView ItemTemplate中的DropDownList操纵

//Fill Array 
private ArrayList GetDummyData() 
    { 
     ArrayList arr = new ArrayList(); 

      arr.Add(new ListItem("Item1", "1")); 
      arr.Add(new ListItem("Item2", "2")); 
      arr.Add(new ListItem("Item3", "3")); 

     return arr; 
    } 

//Fill dropdownlist 
private void FillDropDownList(DropDownList ddl) 
    { 
     ArrayList arr = GetDummyData(); 

     foreach (ListItem item in arr) 
     { 
      ddl.Items.Add(item); 
     } 
    } 

我想要做的就是在asssume GridView控件行[0] i的选择了“Item1的”,所以行[1]中,只有2其余选项 - >“项目2”和项目3"

帮助非常感谢:)

+0

'行[ 0]'和'row [1]'是一行的列还是不同的行('rows [0]')? – 2011-12-19 09:43:23

+0

不同的行..相同的列..(列下拉列表中的项目模板所在的位置) – rofans91 2011-12-19 09:46:10

回答

2

你可以处理RowDataBound事件。

例如(未测试,asssuming的数据源是一个DataTable和你的DropDownList的ID是ddl):

void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
    var thisRow = (DataRowView)e.Row.DataItem; 
    var source = thisRow.DataView; 
    var lastRowIndex = e.Row.DataItemIndex -1; 
    DataRowView lastRow = null; 
    var ddl = (DropDownList)e.Item.FindControl("ddl"); 
    DropDownList ddlLast = null; 
    if(lastRowIndex>=0){ 
     lastRow = source[lastRowIndex]; 
     ddlLast = (DropDownList)((GridView)sender).Rows[lastRowIndex].FindControl("ddl"); 
     //remove the items of this ddl according to the items of the last dll 
    } 
    } 
} 

你应该考虑的是,如果你启用了分页这已经样本将无法正常工作,因为Rows属性只返回当前页面的GridViewRows。

编辑:也许一个更好的办法是处理DropDownList的SelectedIndexChanged事件和更新任何下列下拉菜单的ITEMLIST:

protected void DdlSelected(object sender, EventArgs e) 
{ 
    var ddl = (DropDownList)sender; 
    var row = (GridViewRow)ddl.NamingContainer; 
    var grid = (GridView)row.NamingContainer; 
    var index = row.RowIndex + 1; 
    while (index < grid.Rows.Count) { 
     var nextRow = grid.Rows[index]; 
     var nextDdl = (DropDownList)nextRow.FindControl("ddl"); 
     nextDdl.Items.Clear(); 
     foreach (ListItem item in getDllSource()) { 
      if (ddl.SelectedItem == null || !ddl.SelectedItem.Equals(item)) { 
       nextDdl.Items.Add(item); 
      } 
     } 
     index += 1; 
    } 
} 

getDllSource是以下功能:

private List<ListItem> getDllSource() 
{ 
    List<ListItem> items = new List<ListItem>(); 
    ListItem item = new ListItem("Item1", "1"); 
    items.Add(item); 
    item = new ListItem("Item2", "2"); 
    items.Add(item); 
    item = new ListItem("Item3", "3"); 
    items.Add(item); 
    return items; 
} 
+0

嘿谢谢,这是一个非常好的主意(更改选定索引期间的项目列表更改)..我会尝试首先将此想法调整为我的代码。 。:) – rofans91 2011-12-20 02:07:42

+0

嘿,这是完全正常.. thx这么多:) – rofans91 2011-12-21 03:34:05