首页 > 解决方案 > 要将一个 GridView / SqlDataSource 用于相同的查询但不同的 ConnectionStrings?还是每个 ConnectionString 有多个?

问题描述

我对 ASP.NET 和 C# 完全陌生。我想在 GridView 中显示来自多个数据库之一的一些信息。查询在所有情况下都是相同的,但 ConnectionString 是基于 DropDownList 选择的。

我想知道在这种情况下使用的最佳做法是什么?

我尝试了第一种方法,它工作正常,但代码看起来很混乱,因为有很多 GridViews 大部分时间都没有使用。当我尝试第二种方法时,它并不顺利,因为当我尝试以编程方式更改 GridView 的 DataSource 以刷新它时,我不断收到以下错误:

System.InvalidOperationException:DataSource 和 DataSourceID 都在“GridViewCustomers”上定义。删除一个定义。

我使用以下代码以编程方式更改 SqlDataSource 的 ConnectionString 和 GridView 的 DataSource 以刷新它(每次单击搜索按钮时,代码都会检查 DropDownList 并尝试相应地更改连接):


switch (DropDownList1.SelectedValue.ToString())
            {
                case "30":
                    SqlDataSourceCustomers.ConnectionString = ConfigurationManager.ConnectionStrings["DTconnection"].ConnectionString;
                    SqlDataSourceCustomers.SelectCommand = "DisplayCustomer";
                    SqlDataSourceCustomers.SelectCommandType = System.Web.UI.WebControls.SqlDataSourceCommandType.StoredProcedure;
                    SqlDataSourceCustomers.DataBind();
                    GridViewCustomers.DataSource = SqlDataSourceCustomers;
                    GridViewCustomers.DataBind();
                    GridViewCustomers.Visible = true;
                    break;


                case "20":
                    SqlDataSourceCustomers.ConnectionString= ConfigurationManager.ConnectionStrings["DWahconnection"].ConnectionString;
                    SqlDataSourceCustomers.SelectCommand = "DisplayCustomer";
                    SqlDataSourceCustomers.SelectCommandType = System.Web.UI.WebControls.SqlDataSourceCommandType.StoredProcedure;
                    SqlDataSourceCustomers.DataBind();
                    GridViewCustomers.DataSource = SqlDataSourceCustomers;
                    GridViewCustomers.Visible = true;
                    break;

                default:
                    GridViewCustomers.Visible = false;          
                    break;
            }

标签: c#asp.netgridviewsqldatasource

解决方案


推荐阅读