下拉框绑定数据后如何再加入一项
我这有两种方法 一种是从后台加,还有一种是从前台加
一 是从后台加入 方法如下
前台下拉框:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False" AppendDataBoundItems="True">
</asp:DropDownList>
后台绑定代码
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlmessage();
this.DropDownList1.Items.Insert(0, "--请选择--");
}
}
protected void ddlmessage()
{
string strcon = @"data source=PWGO7I3HGBSSP5C\SQLEXPRESS; database=test;Persist Security Info=true;User Id=sa;Password=123;";
SqlConnection sqlcnn = new SqlConnection(strcon);
SqlCommand sqlcmm = sqlcnn.CreateCommand();
sqlcmm.CommandText = "select * from ddl";
SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
DataSet dt = new DataSet();
da.Fill(dt);
this.DropDownList1.DataSource = dt.Tables[0];
this.DropDownList1.DataTextField = "Role";
this.DropDownList1.DataValueField = "Id";
this.DropDownList1.DataBind();
//this.DropDownList1.Items.Insert(0, "--请选择--");
}
二 ,第二种方法就需要改dropdownlist 的一个属性了!
方法如下;<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="False" AppendDataBoundItems="True">
<asp:ListItem Text="--请选择--" Value="0"></asp:ListItem>
</asp:DropDownList>
在绑定好数据后,直接这样给下拉框添加项,你在运行的时候是不会起到作用的,所以我们需要修改一个属性
AppendDataBoundItems=true;
这样的话,我们想要加的数据就能显示出来了!
后台:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlmessage();
}
}
protected void ddlmessage()
{
string strcon = @"data source=PWGO7I3HGBSSP5C\SQLEXPRESS; d
atabase=test;Persist Security Info=true;User Id=sa;Password=123;";
SqlConnection sqlcnn = new SqlConnection(strcon);
SqlCommand sqlcmm = sqlcnn.CreateCommand();
sqlcmm.CommandText = "select * from ddl";
SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
DataSet dt = new DataSet();
da.Fill(dt);
this.DropDownList1.DataSource = dt.Tables[0];
this.DropDownList1.DataTextField = "Role";
this.DropDownList1.DataValueField = "Id";
this.DropDownList1.DataBind();
}