Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

asp.net - how to bind a dropdownlist in gridview?

I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,

<asp:TemplateField HeaderText="XYZ">
  <ItemTemplate>
    <asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
  </ItemTemplate> 
</asp:TemplateField>

Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as

<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value"  />

GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.

You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,

  protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Find the drop-down (say in 3rd column)
      var dd = e.Row.Cells[2].Controls[0] as DropDownList;
      if (null != dd) {
         // bind it
      }

      /*
      // In case of template fields, use FindControl
      dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
      */
    }

  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...