使用当前值填充网格视图中下拉列表的默认值

时间:2018-04-20 14:39:56

标签: c# asp.net gridview dropdownbox

经过一些漫长的实验,我发现在aspx端有这行代码:

<EditItemTemplate>  
    <asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px" 
         DataTextField="Project_Owner" DataValueField="Project_Owner" 
         SelectedValue='<%# Bind("Project_Owner") %>' >
    </asp:DropDownList>  
</EditItemTemplate>  

导致索引错误,但删除SelectedValue='<%# Bind("Project_Owner") %>'部分允许gridview正常运行。唯一的事情是,当行进入编辑模式时,下拉列表不会填充当前值。这是空白的。我想用当前值填充它。

在代码隐藏方面,我使用此代码填充下拉列表:

protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
    DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
    DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
    LoadResourceAllocationGrid();
    //DataGrid_ResourceAllocation.DataBind();


    SqlConnection conn = GetConnection();
    int RAC = DataGrid_ResourceAllocation.Rows.Count;

    GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];

    //*********************************************************
    //******** Fill in all your dropdown lists here ***********
    //*********************************************************

    DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
    string ddListVal = ddList.SelectedValue;

    //DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
    if (ddList != null)
    {
        //bind dropdown-list
        string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
        DataSet ds = new DataSet();

        conn.Open();
        SqlCommand cmd = new SqlCommand(sqlStr, conn);
        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        ad.Fill(ds);

        ddList.DataSource = ds;
        ddList.DataTextField = "Project_Owner";
        ddList.DataValueField = "Project_Owner";
        ddList.DataBind();

        //DataRowView dr = e.Row.DataItem as DataRowView;
        //ddList.SelectedItem.Text = dr["category_name"].ToString();
        ddList.SelectedValue = ddListVal;
    }

}

我尝试了“ddListVal”变量,因为我认为它可能有用,但它没有,所以你可以忽略它。

有人可以帮助我让我的下拉列表填充该记录中该字段的当前值吗?

1 个答案:

答案 0 :(得分:1)

此错误是由于:您设置了selectedValeue befor binding dropdownlist。 你可以绑定RowDataBound中的dropdownlist

  def low_ammo(weapon, zombie)
    attachments["weapon.jpg"] = weapon.picture_file
    mail to: zombie.email, subject: "#{weapon.name} has low ammo"
  end