0

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

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

  • 我是否为每个 ConnectionString 创建多个 SqlDataSources / GridViews 并根据 DropDownList 选择更改哪个可见或隐藏?

  • 还是我只创建一个 SqlDataSource / GridView 并根据 DropDownList 选择以编程方式更改 ConnectionString?

我尝试了第一种方法,它工作正常,但代码看起来很混乱,因为有很多 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;
            }
4

0 回答 0