gpt4 book ai didi

asp.net - 如何将下拉列表的所有项目获取到gridview?

转载 作者:行者123 更新时间:2023-12-04 04:48:04 24 4
gpt4 key购买 nike

我需要在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();


}

最佳答案

你需要一个循环:

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);

关于asp.net - 如何将下拉列表的所有项目获取到gridview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17878983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com