Click here to Skip to main content
15,896,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to bind data wih listitem with dropdownliat

i cant bind the data from database

the code is like:-

XML
<asp:TemplateField HeaderText="Type">
<EditItemTemplate>
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type" SelectedValue='<%# Eval("type") %>'>
  <asp:ListItem  Selected='<%# Eval("type") %>' ></asp:ListItem>
  </asp:DropDownList>

</EditItemTemplate>
<ItemTemplate>
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("type") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList>

</FooterTemplate>
</asp:TemplateField>


and the error will come like this:-
XML
Error   2   Literal content ('</asp:ListItem>') is not allowed within a 'System.Web.UI.WebControls.ListItemCollection'. C:\Documents and Settings\Harry\My Documents\Visual Studio 2005\example8\Default.aspx   72



so how to bind data with database???


thank you
Posted

1 solution

Hi,

Here's a small sample:

SqlConnection con = new SqlConnection("SOME CONNECTION STRING HERE");
SqlCommand cmd = new SqlCommand("select FieldName from TableName", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "FieldName"; // FieldName of Table in DataBase
DropDownList1.DataValueField = "FieldName"; // FieldName of Table in DataBase
DropDownList1.DataBind();

Read more about the datasource property here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedataboundcontrol.datasource.aspx[^]

If you need to set one of the element to selected then after binding (could be the databound event of teh dropdownlist) you can find the correct element and set it to selected.

Regards
Joachim
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900