Dropdownlist所选项目文本始终返回第一个项目文本
本文关键字:项目 文本 返回 第一个 Dropdownlist 选项 | 更新日期: 2023-09-27 17:58:06
我正在使用此代码填充数据库中的dropdownlist。
public void fillcountry()
{
BL obj = new BL();
DataSet ds = obj.dss("select * from Country ");
drplistcountry.DataSource = ds;
drplistcountry.DataTextField = "CountryName";
drplistcountry.DataValueField = "CountryId";
drplistcountry.DataBind();
drplistcountry.Items.Insert(0, new ListItem("--Select--", "0"));
}
我在page load()事件中使用这个fillcountry()。和在按钮点击事件上重新输出selecteditm.text
drplistcountry总是显示第一个索引文本,如何解决?
In.aspx页面:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default"
EnableViewState="true" %>
对于Dropdownlist控件将EnableViewState属性设置为true。
在.aspx.cs页面中:
在PageLoad事件中检查以下内容:
if(!IsPostBack)
{
fillcountry();
}
试试这个代码
你应该只调用这个函数一次。
public void fillcountry()
{
BL obj = new BL();
DataSet ds = obj.dss("select * from Country ");
drplistcountry.DataSource = ds;
drplistcountry.DataTextField = "CountryName";
drplistcountry.DataValueField = "CountryId";
drplistcountry.DataBind();
drplistcountry.Items.Insert(0, new ListItem("--Select--", "0"));
drplistcountry.SelectedIndex = drplistcountry.Items.IndexOf(drplistcountry.Items.FindByText("--Select--"));
}
一种简单的方法您可以使用中继器在html代码中进行选择,如
<select id="ddlAlbum" class="form-control" name="Cat">
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<option value='<%#Eval("CatID") %>'>
<%#Eval("Title") %>
</option>
</ItemTemplate>
</asp:Repeater>
</select>
使用ado.net 从数据库获取数据
public void fillAlbum()
{
SqlConnection myconnection = new SqlConnection("Data Source=.;Initial Catalog=person;Integrated Security=True");
SqlDataAdapter myadapter = new SqlDataAdapter("Select CatID,Title from Category", myconnection);
DataTable dt = new DataTable();
myadapter.Fill(dt);
rpt.DataSource = dt;
rpt.DataBind();
}
以及获取所选值。选择元素名称为("cat")因此
string cat = Request.Form["Cat"];
并简单地存储到数据库
SqlConnection myconnection = new SqlConnection("Data Source=.;Initial Catalog=person;Integrated Security=True");
SqlCommand mycommand = new SqlCommand("insert into Picture(Title,Pic,CatID) values(@pname,@pic,@cat)", myconnection);
mycommand.Parameters.AddWithValue("pname", txtname.Text.Trim());
mycommand.Parameters.AddWithValue("pic", path);
string cat = Request.Form["Cat"];
mycommand.Parameters.AddWithValue("cat", cat.ToString());
myconnection.Open();
mycommand.ExecuteNonQuery();
myconnection.Close();
它很简单,但很难找到,请检查所有项的值Datavaluefield
不应为空或null。
平均值:
ddl_Name.DataTextField = "NAME";
ddl_Name.DataValueField = "Roll";
如果值为空,则表示您无法只获取第一个项目。
DropdownList所选项目文本值的工作方式如下。
String value="India";
drplist.SelectedIndex = drplist.Items.IndexOf(drplist.Items.FindByText(value));
我也面临着同样的问题,但在我的情况下,所有项目的下拉值都是相同的,这导致了问题。所以,请确保您正确绑定了下拉列表。
:)