如何将Item添加到SqlDataSource数据绑定列表

时间:2022-04-22 15:54:42

I am lazy - and I am using a SQLDataSource to populate my dropdownLists.

我很懒 - 我正在使用SQLDataSource来填充我的dropdownLists。

The Databind event for the databound objects is called before the Page.PreRender so I am doing something like this in the PreRender eventHandler:

在Page.PreRender之前调用数据绑定对象的Databind事件,所以我在PreRender eventHandler中执行类似这样的操作:

private void InitializeDropDown()
        {
            this.myDropDown.Items.Insert(0, new ListItem("-- Select something --"));
        }

I know I can set AppendDataBound items to true and hardcode my custom item in the markup but before reverting to that I'd like to understand why what I am doing is not working.

我知道我可以将AppendDataBound项设置为true并在标记中硬编码我的自定义项,但在恢复之前我想了解为什么我在做什么不起作用。

It usually works when I bind stuff dynamically like this:

它通常在我动态绑定东西时有效:

myDropDown.DataTextField = "whatever";
myDropDown.DataValueField = "ID";
myDropDown.DataSource = GetStuff();
myDropDown.DataBind();
myDropDown.Items.Insert(0, "-- Select something --");

What I am doing should be equivalent - only difference is I am using a SQLDataSource.

我正在做的事情应该是等价的 - 唯一的区别是我使用的是SQLDataSource。

Any help appreciated!

任何帮助赞赏!

2 个解决方案

#1


Put your insert line on the OnSelected method of the datasource

将插入行放在数据源的OnSelected方法上

myDropDown.Items.Insert(0, "-- Select something --");

myDropDown.Items.Insert(0,“ - 选择一些东西 - ”);

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.selected.aspx

#2


I set AppendDataBoundItems="true" for the dropDwonList and it works like charme! I thought it was supposed to be used only in presence of hardcoded list items in the markup. I was wrong.

我为dropDwonList设置AppendDataBoundItems =“true”,它就像魅力一样!我认为它应该仅在标记中存在硬编码列表项时使用。我错了。

#1


Put your insert line on the OnSelected method of the datasource

将插入行放在数据源的OnSelected方法上

myDropDown.Items.Insert(0, "-- Select something --");

myDropDown.Items.Insert(0,“ - 选择一些东西 - ”);

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.selected.aspx

#2


I set AppendDataBoundItems="true" for the dropDwonList and it works like charme! I thought it was supposed to be used only in presence of hardcoded list items in the markup. I was wrong.

我为dropDwonList设置AppendDataBoundItems =“true”,它就像魅力一样!我认为它应该仅在标记中存在硬编码列表项时使用。我错了。