如何为DropDownList设置默认选定索引 [英] How to Set Default Selected Index For DropDownList

查看:85
本文介绍了如何为DropDownList设置默认选定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个下拉列表,当页面加载时,我想设置要选择的下拉列表的第一个选项。然后我将创建一个字符串,获取第一个选项文本,并根据第一个选项文本创建图表,然后在Web上显示图表。用户无需点击任何内容,首次加载页面时,应根据下拉列表中的第一个选项文本显示正确的图表。





这是我的代码:

 protected void Page_Load(object sender,EventArgs e)
{
if(!IsPostBack)
{
BindDropDownList();
DropDownList.ClearSelection();
DropDownList.SelectedIndex = 1;
BindChart();
}
}


//我如何填充下拉列表:根据从列表框中选择的内容,我将这些选项绑定到下拉列表

public void BindDropDownList()
{
DateTime choosenDate = DateTime.MinValue;

使用(SqlConnection conn = new SqlConnection(dbConn))
{
using(SqlCommand cmd = new SqlCommand(spretrieve,conn))
{
//丢失以保存值
列出< DateTime > listCopy = new List < DateTime > ();
DateTime dt;
字符串值= String.Join(,,ListBox1.Items.Cast < ListItem > ()。其中​​(i => i.Selected).Select(i => i.Text));
if(values.Contains(Select All))
{
//循环遍历列表框中的每个项目,然后将其添加到列表
foreach(ListBox1中的ListItem li)。项目)
{
if(DateTime.TryParse(li.Text,out dt))
{
listCopy.Add(dt);
}
}
}
其他
{
//循环浏览列表框中的每个项目,然后将其添加到列表
foreach(ListItem li在ListBox1.Items)
{
//检查项目是否被选中
if(li.Selected == true)
{
//将项目添加到列表
listCopy.Add(DateTime.Parse(li.Text));
}
}
}

//比较和排序,以便最新日期排在最前面
listCopy.Sort((x,y)= > y.CompareTo(x));
//清除下拉列表中的项目
DropDownList.Items.Clear();
//将数据源设置为dropdownlist
DropDownList.DataSource = listCopy;
//在dropdownlist中设置dateformatstring
DropDownList.DataTextFormatString ={0:dd-MMM-yyyy};
//绑定下拉列表
DropDownList.DataBind();

//我如何基于下拉列表选择生成图表选项

public void BindChart()
{
//创建新的TabContainer
AjaxControlToolkit.TabContainer container = new AjaxControlToolkit.TabContainer();
container.ID =TabContainer;
container.EnableViewState = false;
container.Tabs.Clear();

string selectedItem = DropDownList.SelectedItem.ToString();

if(ListBox1.SelectedValue ==Select All)
{
foreach(ListBox1.Items中的ListItem项)
{
if(item) .Text ==全选)
{
继续;
}
AjaxControlToolkit.TabPanel panel = new AjaxControlToolkit.TabPanel();
panel.HeaderText + = item.Text;
container.Tabs.Add(panel);

Label tabContent = new Label();
tabContent.ID + = item.Text;
tabContent.Text + = item.Text;

DataTable tg = new DataTable();
DataRow博士;
tg.Columns.Add(new DataColumn(DATE));
tg.Columns.Add(new DataColumn(STATUS,typeof(string)));
tg.Columns.Add(new DataColumn(TITLE,typeof(string)));
tg.Columns.Add(new DataColumn(TYPE,typeof(string)));
tg.Columns.Add(new DataColumn(MAX,typeof(int)));
tg.Columns.Add(new DataColumn(MIN,typeof(int)));
tg.Columns.Add(new DataColumn(AVG,typeof(int)));
tg.Columns.Add(new DataColumn(PERCENTILE25,typeof(int)));
tg.Columns.Add(new DataColumn(PERCENTILE50,typeof(int)));
tg.Columns.Add(new DataColumn(PERCENTILE75,typeof(int)));
foreach(GridView1.Rows中的GridViewRow gvr)
{
if(gvr.Cells [2] .Text == tabContent.Text.ToString()&& gvr.Cells [0 ] .Text == chartJobRunDate.ToString())
{
dr = tg.NewRow();
dr [DATE] = gvr.Cells [0] .Text;
dr [STATUS] = gvr.Cells [1] .Text;
dr [TITLE] = gvr.Cells [2] .Text;
dr [TYPE] = gvr.Cells [3] .Text;
dr [MAX] = int.Parse(gvr.Cells [4] .Text);
dr [MIN] = int.Parse(gvr.Cells [5] .Text);
dr [AVG] = int.Parse(gvr.Cells [6] .Text);
dr [PERCENTILE25] = int.Parse(gvr.Cells [7] .Text);
dr [PERCENTILE50] = int.Parse(gvr.Cells [8] .Text);
dr [PERCENTILE75] = int.Parse(gvr.Cells [9] .Text);
tg.Rows.Add(dr);
}
}

if(tg.Rows.Count> 0)
{
Chart Chart1 = new Chart();
Chart1.DataSource = tg;

Chart1.Series.Add(new Series());
Chart1.Series [0] .ChartType = SeriesChartType.BoxPlot;
列表< 对象 > lst = tg.AsEnumerable()。ToList < object > ();

foreach(tg.Rows中的DataRow行)
Chart1.Series [0] .Points.AddXY(row [STATUS],new object [] {row [MAX] ,row [MIN],row [AVG],row [PERCENTILE25],row [PERCENTILE50],row [PERCENTILE75]});

Chart1.Series [0] .ChartType = SeriesChartType.BoxPlot;

Title title = new Title();
title.Text =(tg.Rows [0] [TITLE]。ToString());
Chart1.Titles.Add(title);

//创建chartareas
ChartArea ca = new ChartArea();
ca.AxisX = new Axis();
ca.AxisY = new Axis();
ca.AxisY.MajorGrid.Enabled = false;

Chart1.ChartAreas.Add(ca);

// databind
Chart1.DataBind();
Chart1.Visible = true;

panel.Controls.Add(Chart1);

}
}
}
}
}



问题:如何设置选择下拉列表的第一个选项,然后使用字符串检索第一个选项的文本,然后创建图表基于此第一个选项,并在页面首次加载时显示图表而无需点击任何内容?





感谢有人可以帮助我,非常感谢!! :)



问候,



Felicia

解决方案
执行如下操作

  //  首先绑定DropDownList  
BindDropDownList();
// 现在设置selectedindex
DropDownList1.SelectedIndex = 0 ; // 选择DropDownList的索引
// 现在你可以调用依赖于DropDownList选择索引的其他数据绑定
LoadCahrt();


嗯,这是一个疯狂的猜测。



尝试在页面加载前绑定下拉列表。

写下你的下载绑定在 Page.PreInit [ ^ ]并设置 selectedIndex = 0



Page.Load 调用 LoadChart();



- KR


您应该在页面加载事件中加载下拉列表后绑定相关方法,同时需要调用关联dropdownselectedIndex事件中的ed方法。



受保护的 void  Page_Load(< span class =code-keyword> object  sender,EventArgs e)
{
if (!IsPostBack)
{
Bind_DropDown();
Bind_RelatedMethods();
}
}
受保护 void ddl_OnSelectedIndexChanged( object sender,EventArgs e)
{
Bind_RelatedMethods();
}


Hi Members,

I have a dropdownlist, when the page is loaded, I want to set the first option of the dropdownlist to be selected. Then I will create a string, get the first option text, and create charts based on the first option text, then display the charts on the web. User does not have to click on anything, when the page is first loaded correct charts should be shown based on the first option text in the dropdownlist.


This is my codes:

protected void Page_Load(object sender, EventArgs e)
        {
if (!IsPostBack)
   {
                        BindDropDownList();
                        DropDownList.ClearSelection();
                        DropDownList.SelectedIndex = 1;
                        BindChart();
                    }
}


//How I populate the dropdownlist: Based on what is selected from a listbox, I will bind those options into the dropdownlist

public void BindDropDownList()
        {
            DateTime choosenDate = DateTime.MinValue;

            using (SqlConnection conn = new SqlConnection(dbConn))
            {
                using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
                {
                    //Lost to hold the values
                    List<DateTime> listCopy = new List<DateTime>();
                    DateTime dt;
                    string values = String.Join(", ", ListBox1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Text));
                    if (values.Contains("Select All"))
                    {
                        //Loop through each items in listbox and then add it to list
                        foreach (ListItem li in ListBox1.Items)
                        {
                            if (DateTime.TryParse(li.Text, out dt))
                            {
                                listCopy.Add(dt);
                            }
                        }
                    }
                    else
                    {
                        //Loop through each items in listbox and then add it to list
                        foreach (ListItem li in ListBox1.Items)
                        {
                            //check if item is selected
                            if (li.Selected == true)
                            {
                                //add items to list
                                listCopy.Add(DateTime.Parse(li.Text));
                            }
                        }
                    }

                    //compare and sort so that the latest date comes on top
                    listCopy.Sort((x, y) => y.CompareTo(x));
                    //clear the items in dropdownlist
                    DropDownList.Items.Clear();
                    //set the datasource to dropdownlist
                    DropDownList.DataSource = listCopy;
                    //set the dateformatstring in dropdownlist
                    DropDownList.DataTextFormatString = "{0:dd-MMM-yyyy}";
                    //Bind the dropdownlist
                    DropDownList.DataBind();

//how I generate the chart based on dropdownlist selected option

public void BindChart()
        {
            //Create new TabContainer
            AjaxControlToolkit.TabContainer container = new AjaxControlToolkit.TabContainer();
            container.ID = "TabContainer";
            container.EnableViewState = false;
            container.Tabs.Clear();

            string selectedItem= DropDownList.SelectedItem.ToString();

            if (ListBox1.SelectedValue == "Select All")    
            {
                foreach (ListItem item in ListBox1.Items)
                {
                    if (item.Text == "Select All")
                    {
                        continue;
                    }
                    AjaxControlToolkit.TabPanel panel = new AjaxControlToolkit.TabPanel();
                    panel.HeaderText += item.Text;
                    container.Tabs.Add(panel);

                    Label tabContent = new Label();
                    tabContent.ID += item.Text;
                    tabContent.Text += item.Text;

                    DataTable tg = new DataTable();
                    DataRow dr;
                    tg.Columns.Add(new DataColumn("DATE"));
                    tg.Columns.Add(new DataColumn("STATUS", typeof(string)));
                    tg.Columns.Add(new DataColumn("TITLE", typeof(string)));
                    tg.Columns.Add(new DataColumn("TYPE", typeof(string)));
                    tg.Columns.Add(new DataColumn("MAX", typeof(int)));
                    tg.Columns.Add(new DataColumn("MIN", typeof(int)));
                    tg.Columns.Add(new DataColumn("AVG", typeof(int)));
                    tg.Columns.Add(new DataColumn("PERCENTILE25", typeof(int)));
                    tg.Columns.Add(new DataColumn("PERCENTILE50", typeof(int)));
                    tg.Columns.Add(new DataColumn("PERCENTILE75", typeof(int)));
                    foreach (GridViewRow gvr in GridView1.Rows)
                    {
                        if (gvr.Cells[2].Text == tabContent.Text.ToString() && gvr.Cells[0].Text == chartJobRunDate.ToString())
                        {
                            dr = tg.NewRow();
                            dr["DATE"] = gvr.Cells[0].Text;
                            dr["STATUS"] = gvr.Cells[1].Text;
                            dr["TITLE"] = gvr.Cells[2].Text;
                            dr["TYPE"] = gvr.Cells[3].Text;
                            dr["MAX"] = int.Parse(gvr.Cells[4].Text);
                            dr["MIN"] = int.Parse(gvr.Cells[5].Text);
                            dr["AVG"] = int.Parse(gvr.Cells[6].Text);
                            dr["PERCENTILE25"] = int.Parse(gvr.Cells[7].Text);
                            dr["PERCENTILE50"] = int.Parse(gvr.Cells[8].Text);
                            dr["PERCENTILE75"] = int.Parse(gvr.Cells[9].Text);
                            tg.Rows.Add(dr);
                        }
                    }

                    if (tg.Rows.Count > 0)
                    {
                        Chart Chart1= new Chart();
                        Chart1.DataSource = tg;

                        Chart1.Series.Add(new Series());
                        Chart1.Series[0].ChartType = SeriesChartType.BoxPlot;
                        List<object> lst = tg.AsEnumerable().ToList<object>();

                        foreach (DataRow row in tg.Rows)
                            Chart1.Series[0].Points.AddXY(row["STATUS"], new object[] { row["MAX"], row["MIN"], row["AVG"], row["PERCENTILE25"], row["PERCENTILE50"], row["PERCENTILE75"] });

                        Chart1.Series[0].ChartType = SeriesChartType.BoxPlot;

                        Title title = new Title();
                        title.Text = (tg.Rows[0]["TITLE"].ToString());
                        Chart1.Titles.Add(title);

                        //create chartareas
                        ChartArea ca = new ChartArea();
                        ca.AxisX = new Axis();
                        ca.AxisY = new Axis();
                        ca.AxisY.MajorGrid.Enabled = false;
   
                        Chart1.ChartAreas.Add(ca);

                        //databind
                        Chart1.DataBind();
                        Chart1.Visible = true;

                        panel.Controls.Add(Chart1);

                    }
                        }
                    }
                }
            }


Question: How to set the first option of the dropdownlist as selected, then use string to retrieve the text of this first option, then create chart based on this first option, and display the chart out when the page is first loaded without having to click on anything?


Appreciate if someone can help me on this, thanks a lot!! :)

Regards,

Felicia

解决方案

in your page load method do as below

//Bind DropDownList first
BindDropDownList(); 
//now set the selectedindex 
DropDownList1.SelectedIndex = 0; // select index of DropDownList
//Now you can call other data bindings which depend on DropDownList selected index
LoadCahrt();


Umm, It's a wild guess.

try to bind the dropdown before the page loads.
Write your dropdown bindin in Page.PreInit[^] and set the selectedIndex = 0.

And on Page.Load call the LoadChart();

-KR


You should bind the related methods after dropdown loaded in page load event at the sametime you need to call the related methods on dropdownselectedIndex event too.

Protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        Bind_DropDown();
        Bind_RelatedMethods();
    }
}
protected void ddl_OnSelectedIndexChanged(object sender, EventArgs e)
{
    Bind_RelatedMethods();
}


这篇关于如何为DropDownList设置默认选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆