像这样解决它:ASPX:
<asp:DropDownList ID="ddlNItems" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlNItems_SelectedIndexChanged">
<asp:ListItem Selected="True">1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True">
<Columns>
<asp:TemplateField HeaderText="Código">
<ItemTemplate>
<asp:TextBox ID="txtCodMuestra" runat="server" Text='<%# Eval("cod") %>' /></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tipo">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlTipo" SelectedValue='<%# Eval("Tipo") %>'>
<asp:ListItem Value="a">A</asp:ListItem>
<asp:ListItem Value="b">B</asp:ListItem>
<asp:ListItem Value="c">C</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
public class Itemx
{
public string cod { get; set; }
public string Tipo { get; set; }
}
public static List<Itemx> LItems
{
get
{
return (List<Itemx>)Session["LItems"];
}
set
{
Session["LItems"]= value;
}
}
void InitializeItems()
{
LItems = new List<Itemx>();
ConfigItems();
}
void ConfigItems()
{
int numitems = Convert.ToInt32(ddlNItems.SelectedValue);
if (LItems.Count > numitems )
{
for (int i = GridView1.Rows.Count; i > numitems; i--)
{
LItems.RemoveAt(i - 1);
}
}
else if (LItems.Count < numitems )
{
for (int i = GridView1.Rows.Count; i < numitems; i++)
{
LItems.Add(new Itemx { Tipo = "a" });
}
}
transferGridtoList();
GridView1.DataSource = LItems;
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
private void transferGridtoList()
{
for (int i = 0; i < LItems.Count && i < GridView1.Rows.Count; i++)
{
LItems[i].cod = ((TextBox)GridView1.Rows[i].Cells[0].Controls[1]).Text;
LItems[i].Tipo = ((DropDownList)GridView1.Rows[i].Cells[1].Controls[1]).SelectedValue;
}
}
protected void ddlNItems_SelectedIndexChanged(object sender, EventArgs e)
{
ConfigItems();
}