日期:2014-05-17  浏览次数:20451 次

listView里动态绑定DropDownList的问题
我想在 listView里动态绑定DropDownList

首先我在Page_Load用Linq的存储过程动态绑定数据上去有userID userName roleName三个字段

 protected void Page_Load(object sender, EventArgs e)
  {
  if(!Page.IsPostBack)
  {
  this.setBind();
  }
  }


public void setBind()
  {
  string id = "2";
  var sysuserinfo = da.showur(id);
  ListView1.DataSource = sysuserinfo;
  ListView1.DataBind();
  }

现在我在<EditItemTemplate>里用LinqDataSource控件绑定一张表roleInfo

<EditItemTemplate>
  <tr style="">
  <td>
  <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="更新" />
  <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="取消" />
  </td>
  <td>
  <asp:Label ID="userIDLabel1" runat="server" Text='<%# Eval("userID") %>' />
  </td>
  <td>
  <asp:TextBox ID="userNameTextBox" runat="server" 
  Text='<%# Bind("userName") %>' />
  </td>
  <td>
  <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="LinqDataSource1" DataTextField="roleName" DataValueField="roleID">
  </asp:DropDownList>
  </td>
  </tr>
  </EditItemTemplate>


现在有两个问题
1.我怎么能动态在在编辑的时候动态的绑定数据上去,在ItemEditing这个事件里面根本找不到DropDownList1这个控件
var roleinfo = da.Sys_RoleInfo;
((DropDownList)ListView1.EditItem.FindControl("DropDownList1")).DataSource = roleinfo;//这一抱空引用

2.如果我不能动态绑定,那么显示信息里有三种角色 管理员 经理 员工,我现在找编辑状态下总DropDownList总是默认为第一个管理员角色,我现在我相如果该用户是经理在DropDownList自动选中经理角色,该用户是员工在DropDownList自动选中员工角色
我用过SelectedValue='<%#Bind("roleName") %>'这个属性但报错
“DropDownList1”有一个无效 SelectedValue,因为它不在项目列表中
参数名: value 


------解决方案--------------------
protected void ListView1_ItemInserting(object sender, ListViewInsertEventArgs e)
{
DropDownList ddl= e.Item.FindControl("ddl") as DropDownList;
}

protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
Bind();
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DropDownList ddl= ListView1.Items[e.ItemIndex].FindControl("ddl") as DropDownList;
}
看看页面dropdownlist值