c# - 要将一个 GridView / SqlDataSource 用于相同的查询但不同的 ConnectionStrings?还是每个 ConnectionString 有多个?
问题描述
我对 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;
}
解决方案
推荐阅读
- django - 如何在产品评论中显示评分
- jquery - Drawsvg - 多次回调调用的问题
- node.js - Azure 中托管的节点服务器上的 Websocket 失败
- swift - 如何使用 KolodaView Swift 在卡片的左右拖动中点击喜欢和不喜欢 API
- python - django 如何从视图中获取装饰器中的 kwargs
- python-3.x - 使用python下载图像
- python-3.x - 使用 aws-python-sdk 读取 json 时出错
- android - flutter_blue set_notification_error,找不到特征的 CCCD 描述符
- httpurlconnection - 关于 HttpURLConnection 和 HTTP2 的查询
- python - 在线校验和计算器如何工作?