我需要在asp.net中显示ddl到gridview的所有项目。怎么实现呢? 我的aspx代码是
<form id="form1" runat="server">
<asp:DropDownList ID="DDLCountry" runat="server" OnSelectedIndexChanged="DDLCountry_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem>--Select-- </asp:ListItem>
<asp:ListItem>India</asp:ListItem>
<asp:ListItem>Australia</asp:ListItem>
<asp:ListItem>Pakistan</asp:ListItem>
</asp:DropDownList>
<div>
<asp:GridView ID="Grd1" runat="server">
</asp:GridView>
</div>
</form>
我的aspx.cs代码是
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Country", typeof(string)));
DataRow dr = dt.NewRow();
dr["Country"] = DDLCountry.Items;
dt.Rows.Add(dr);
Grd1.DataSource = dt;
Grd1.DataBind();
}
答案 0 :(得分:3)
你需要一个循环:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Country", typeof(string)));
foreach(ListItem item in DDLCountry.Items)
{
DataRow dr = dt.NewRow();
dr.SetField("Country",item .Text);
dt.Rows.Add(dr);
}
Grd1.DataSource = dt;
Grd1.DataBind();
或最小化版本:
DataTable dt = new DataTable();
dt.Columns.Add("Country"); // string is default
foreach (string country in DDLCountry.Items.Cast<ListItem>().Select(i => i.Text))
dt.Rows.Add(country);