あなたがまだ答えを探している場合、これは詳細な例です:
出力
ASPX
<asp:GridView runat="server" ID="gridView" AutoGenerateColumns="False"
onrowdatabound="gridView_RowDataBound"
onrowcancelingedit="gridView_RowCancelingEdit"
onrowediting="gridView_RowEditing" onrowupdating="gridView_RowUpdating">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField="LastName" />
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country.Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlCountries" DataTextField="Name" DataValueField="ID">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
コードビハインド
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var t = e.Row.RowType;
if (t == DataControlRowType.DataRow)
{
if (this.gridView.EditIndex >= 0 && e.Row.RowIndex == this.gridView.EditIndex)
{
var d = e.Row.FindControl("ddlCountries") as DropDownList;
var em = e.Row.DataItem as Employee;
d.DataSource = this.GetCountries();
d.DataBind();
d.SelectedValue = em.Country.ID.ToString();
}
}
}
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
this.gridView.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void gridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.gridView.EditIndex = -1;
this.BindGrid();
}
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var row = this.gridView.Rows[e.RowIndex];
var c = (DropDownList)row.FindControl("ddlCountries");
var newValue = c.SelectedValue;
// save the changes
this.gridView.EditIndex = -1;
this.BindGrid();
}