Reputation:
I need to display all the items of a ddl to gridview in asp.net. How to achieve that? My aspx code is
<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>
My aspx.cs code is
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();
}
Upvotes: 2
Views: 9032
Reputation: 460068
You need a loop:
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();
or the minimized version:
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);
Upvotes: 3