简体   繁体   English

在ASP.NET的C#中更新DropDownList的DataSource

[英]Updating the DataSource of a DropDownList in ASP.NET's C#

I have an edit form that uses a DropDownList, connected to a SQL server table using a DataSource. 我有一个使用DropDownList的编辑表单,使用DataSource连接到SQL服务器表。 This edit form allows users to set the table's "IsDeleted" column value to 1, which would then hide it from all of the application's queries. 此编辑表单允许用户将表的“IsDeleted”列值设置为1,然后将其隐藏在所有应用程序的查询中。 (So the transaction still exists in the database, but not in the application) (所以事务仍然存在于数据库中,但不存在于应用程序中)

The problem I've encountered with this is that if the page on which the edit form is is not left entirely, and then entered again, the entry still remains in the DataSource. 我遇到的问题是,如果编辑表单所在的页面未完全保留,然后再次输入,则该条目仍保留在DataSource中。

So essentially, the DataSource is not updating. 基本上,DataSource没有更新。 (It's not running its select statement and repopulating until the whole page is reloaded). (它不会运行其select语句并重新填充,直到重新加载整个页面)。 I've tried to use a page refresh and it doesn't seem to work, only going to a different page entirely and then coming back seems to update the DataSource. 我试图使用页面刷新,它似乎不起作用,只是完全转到另一个页面然后回来似乎更新数据源。

How would I refresh the contents of the DataSource programmatically without having to recreate the entire DataSource itself? 如何以编程方式刷新DataSource的内容而无需重新创建整个DataSource本身?

You might want to add some code next time. 您可能希望下次添加一些代码。 My best guess for now is that you're not doing anything OnPostback. 我现在最好的猜测是你没有做任何OnPostback。

So I eventually resorted to doing what I did not want to do in the hopes that there would be a "Best-practice" way to do it (and one hopefully already built-in into DataSources), but it seems that was not to be. 所以我最终采取了我不想做的事情,希望有一种“最佳实践”的方式来实现它(希望已经内置到DataSources中),但似乎不是。

All it took was to re-assign the DataSource's parameters to it again and then assign the DataSource back to the DropDownList, as if I were creating a new one. 所需要的只是再次将DataSource的参数重新分配给它,然后将DataSource分配回DropDownList,就像我创建一个新的一样。

I created the following method, which I then called at the end of my Delete button's event. 我创建了以下方法,然后在删除按钮的事件结束时调用该方法。

protected void DropDownList_Reload()
    {
        MyDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
        MyDataSource.SelectCommand = "SELECT * FROM [tblMyTable] WHERE [IsDeleted] <> 1";

        cbxDropDownList.DataSourceID = "MyDataSource";
        cbxDropDownList.DataTextField = "MyHeader";
        cbxDropDownList.DataValueField = "MyHeader";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM