以格式绑定gridview中edititem模板中的下拉列表

时间:2016-01-27 09:05:33

标签: c# asp.net

我正在尝试在RowBound事件下的EditItemTemplate下绑定Gridview中的dropdownlist。但它在下拉列表中给出了空白行:这是我的设计

<asp:TemplateField HeaderText="Description">
   <ItemTemplate>
      <asp:Label ID="lblDescription" runat="server" Text='<%# Bind("Description") %>' Width="400px"></asp:Label>
   </ItemTemplate>
   <EditItemTemplate>
      <asp:Label ID="lblCity" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
      <asp:DropDownList ID="ddlCities" runat="server" Width="400px"></asp:DropDownList>
   </EditItemTemplate>
   <FooterTemplate>
      <asp:DropDownList ID="ddlNewDescFooter" runat="server" Width="400px" OnSelectedIndexChanged="ddlCitiesFooter_SelectedIndexChanged">
      </asp:DropDownList>
   </FooterTemplate>
</asp:TemplateField>

现在这是我的Row DataBound事件:

protected void grdFerries_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowState == DataControlRowState.Edit)
   {
       DropDownList ddlCities = (DropDownList)e.Row.FindControl("ddlCities");
       DataAccessClass DAC = new DataAccessClass();
       string Query = "select description from JoursFeries where Year(JoursFeries.date) >= Year(GETDATE()) order by date asc";
       DataTable dtddl = DAC.ReturnDatatablefromQuery(Query, DBConnectionString);
       ddlCities.DataSource = dtddl;
       ddlCities.DataTextField = "description";
       ddlCities.DataValueField = "description";
       ddlCities.DataBind();
       ddlCities.Items.Insert(0, new ListItem("--Select--", "0"));
   }
}

我得到空白的Dropdownlist。请帮助。

1 个答案:

答案 0 :(得分:1)

那是因为您编写的代码块永远不会被执行。您需要检查行是DataRow而不是状态。您必须检查被限制的行是否处于编辑模式。这应该适合你: -

if (e.Row.RowType == DataControlRowType.DataRow && grdFerries.EditIndex == e.Row.RowIndex)
{
   DropDownList ddlCities = (DropDownList)e.Row.FindControl("ddlCities");
   DataAccessClass DAC = new DataAccessClass();
   ..and so on
}