比如你要把DataTable绑定到selKindID这个下拉列表中, 你可以自定义列, 先往DataTable里填几行自定义的值, 再去绑定DataRow dr = dsKinds.Tables[0].NewRow();
dr["KindID"] = "-100";
dr["KindName"] = "所有类别";
dsKinds.Tables[0].Rows.Add(dr);
selKindID.DataSource = dsKinds.Tables[0];
selKindID.DataTextField = "KindName";
selKindID.DataValueField = "KindID";
dr["KindID"] = "-100";
dr["KindName"] = "所有类别";
dsKinds.Tables[0].Rows.Add(dr);
selKindID.DataSource = dsKinds.Tables[0];
selKindID.DataTextField = "KindName";
selKindID.DataValueField = "KindID";
selKindID.item.insert(0,newlistitem("text","value"))这就样就行了,0代表添加到第一个,后面的就不用说了吧
但要注意写了都少,写大第几个了;
简单明晰的写法:
DropDownList.item.Add("项名");
DropDownList.item[i].value("值");
for(int i=0;i<ds1.Tables["Authors"].Rows.Count;i++){
DataRow dr=ds1.Tables["Authors"].Rows[i];
DropDown1.Items.Add(new ListItem(dr["State"].ToString(), dr["au_id"].ToString()));
}
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
String selectCmd = "select * from Authors";
SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;database=pubs;Integrated Security=SSPI");
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
DataSet ds1 = new DataSet();
myCommand.Fill(ds1, "Authors");
for(int i=0;i<ds1.Tables["Authors"].Rows.Count;i++){
DataRow dr=ds1.Tables["Authors"].Rows[i];
DropDown1.Items.Add(new ListItem(dr["State"].ToString(), dr["au_id"].ToString()));
}
}
</script>
</head>
<body>
<h3><font face="Verdana">DropDownList Example</font></h3>
<form runat=server>
<asp:DropDownList id=DropDown1 runat="server">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:DropDownList>
<p>
<asp:Label id=Label1 font-name="Verdana" font-size="10pt" runat="server">
Select a value from the list
</asp:Label>
</form>
</body>
</html>