【发布时间】:2014-03-15 18:15:39
【问题描述】:
我在 asp.net 中创建了一个下拉组合框。这里是:
<asp:ComboBox ID="dropdown_course3" runat="server" AutoPostBack="False"
DropDownStyle="DropDownList"
AutoCompleteMode="Suggest" CaseSensitive="False"
ItemInsertLocation="Append">
</asp:ComboBox>
然后我的页面中有一个按钮,当我单击它时,我想获取组合框中所选项目的值。该按钮导致回发。这是我的代码:
protected void button_conflict_check_button_Click(object sender, EventArgs e)
{
string dr3 = dropdown_course3.Text;
}
但这会返回一个空字符串,即使它不应该为空。另外,我尝试了 selectedItem 并返回 null。谁能帮我解决这个问题?
另外,这是我填充组合框的方式:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable subjects = new DataTable();
CommonFunctions.con.ConnectionString = CommonFunctions.getConnectionString();
CommonFunctions.con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [crn], [subj], [numb], [section] FROM Courses", CommonFunctions.con);
adapter.Fill(subjects);
foreach (DataRow dr in subjects.Rows)
{
string displayVal = dr["subj"].ToString() + " " + dr["numb"].ToString() + " " + dr["section"].ToString();
dropdown_course1.Items.Add(new ListItem(displayVal));
dropdown_course2.Items.Add(new ListItem(displayVal));
dropdown_course3.Items.Add(new ListItem(displayVal));
}
}
catch (Exception ex)
{
// Handle the error
}
// Add the initial item - you can add this even if the options from the
// db were not successfully loaded
CommonFunctions.con.Close();
}
}
谢谢
【问题讨论】:
-
为什么不希望它是空的?您发布的代码没有显示任何添加到列表或选择的内容,所以我希望它是空的。
-
@ChrisBallard 我编辑并添加了我如何填充组合框。然后我选择一个项目,单击按钮。然后由于选择了一个项目,我不希望选择的值为空
-
谢谢!你确定
SelectedItem?如果您在按钮处理程序中添加一个var item = dropdown_course3.SelectedItem,并在其上放置一个断点,那么项目是否是null? -
@ChrisBallard 我相信我找到了问题所在。由于我在页面加载和 if(!Page.IspostBack) 内部填充列表,因此当我单击按钮时,不会再次加载值并且组合框似乎为空。当我使用普通 asp:dropdownlist 时效果很好,但是当我更改为组合框时,加载的值在页面回发时消失
-
嗯,有道理。哎呀。