根据数据值在下拉菜单中设置所选项目 [英] Setting selected item in a dropdown based on data value
问题描述
我正在设置一个页面来显示基于联赛的比赛结果,并且系统存储了多个赛季的结果.
我有一个表(tblSeason),其中存储SeasonID,SeasonName和一个称为Current的位字段-仅设置了一条记录-这是结果的默认季节-这使我可以获取历史数据,当前季节和未来季节.我想填充一个下拉列表,将当前季节作为默认选择.
填充下拉列表很容易,但是我无法弄清楚如何预先选择当前季节.
季节表中的数据是这样的
SeasonID,季节,当前
1,"2010/11",0
2,"2011/12",0
3,"2012/13",1
4,"2013/14",0
我使用的SQL字符串是:
从[tblSeason]中选择[SeasonID],[Season],[Current],然后按[Season]排序
下拉列表的标记为:
< asp:DropDownList ID ="ddlSeason" runat ="server" DataSourceID ="sqlSeason"
DataTextField ="Season" DataValueField ="SeasonID"
AutoPostBack ="True" onselectedindexchanged ="ddlLeague_SelectedIndexChanged">
由于我要查找的数据中的值不在下拉列表的文本或值属性中,因此无法使用FindByValue或FindByText方法.我该怎么做?
I am setting up a page to display results from a league based competition, and the system stores results for numerous seasons.
I have a table (tblSeason) that stores SeasonID, SeasonName and a bit field called Current - only one record has the bit set - it is the default season for the results - this allows me to have historic data, the current season, and future seasons. I want to populate a drop down list, with the current season as the default selection.
Populating the dropdown is easy, but I can''t work out how to pre-select the current season.
Data in the season table is like this
SeasonID, Season, Current
1,"2010/11",0
2,"2011/12",0
3,"2012/13",1
4,"2013/14",0
The SQL string I use is:
SELECT [SeasonID], [Season], [Current] FROM [tblSeason] ORDER BY [Season]
The markup for the dropdown list is:
<asp:DropDownList ID="ddlSeason" runat="server" DataSourceID="sqlSeason"
DataTextField="Season" DataValueField="SeasonID"
AutoPostBack="True" onselectedindexchanged="ddlLeague_SelectedIndexChanged">
As the value in the data that I am looking for is not in the text or value propert of the dropdown, I can''t use the FindByValue or FindByText methods. How can I do this?
推荐答案
尝试以下代码:
Try following code:
ddlSeason.SelectedIndex = ddlSeason.Items.IndexOf(ddlSeason.Items.FindByValue("4"));
希望对您有帮助.
〜Amol
Hope this will help you.
~Amol
我创建了一个过程来检索设置了Current标记的seaon,然后将此值与下拉菜单的FindByText方法一起使用:
I created a procedure to retrieve the seaon that has the Current marker set, then used this value with the FindByText method of the dropdown:
string strCurrent = getCurrentSeason();
ddlSeason.SelectedIndex = ddlSeason.Items.IndexOf(ddlSeason.Items.FindByText(strCurrent));
protected string getCurrentSeason()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
conn.Open();
string queryString = "SELECT [Season] FROM tblSeason WHERE [Current] = 1";
SqlCommand command = new SqlCommand(queryString, conn);
string strReturn = "";
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
strReturn = reader.GetString(0);
}
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
return strReturn;
}
这篇关于根据数据值在下拉菜单中设置所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!