【问题标题】:GridView ItemTemplate DropDownList ManipulationGridView ItemTemplate DropDownList 操作
【发布时间】:2011-12-19 09:28:48
【问题描述】:

假设我在我的 gridview 中有模板化的下拉列表(绑定到所有行) 下拉列表通过数组填充..

//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);
        }
    }

我想要做的是假设在gridview row[0]中我选择了“Item1”,所以在row[1]中只剩下2个选项-->“Item2”和Item3“

非常感谢您的帮助。 :)

【问题讨论】:

  • row[0]row[1]是一行的列还是不同的行(rows[0])?
  • 不同的行..相同的列..(下拉列表项模板所在的列)

标签: c# asp.net gridview drop-down-menu itemtemplate


【解决方案1】:

您可以处理RowDataBound 事件。

例如(未测试,假设DataSource是一个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 事件并更新以下任何下拉列表的项目列表:

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;
}

【讨论】:

  • 嘿,谢谢,这是一个非常棒的想法(在选定索引更改期间更新项目列表)。我会先尝试将这个想法调整到我的代码中。:)
猜你喜欢
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多