如何从数据库绑定listitem [英] how to bind listitem from database

查看:129
本文介绍了如何从数据库绑定listitem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将带listitem的数据与dropdownliat绑定

我无法绑定数据库中的数据

代码就像:-

i want to bind data wih listitem with dropdownliat

i cant bind the data from database

the code is like:-

<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:-

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

推荐答案



这是一个小样本:

SqlConnection con =新的SqlConnection("SOME CONNECTION STRING HERE");
SqlCommand cmd =新的SqlCommand(从TableName中选择FieldName",con);
SqlDataAdapter sda =新的SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField ="FieldName"; //数据库中表的FieldName
DropDownList1.DataValueField ="FieldName"; //数据库中表的FieldName
DropDownList1.DataBind();

在此处阅读有关数据源属性的更多信息:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedataboundcontrol.datasource.aspx [
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


这篇关于如何从数据库绑定listitem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆