更改连接字符串,请单击该特定用户
问题描述:
我有一个LinkButton
在我MasterPage
头:更改连接字符串,请单击该特定用户
<asp:LinkButton ID="LinkSwitchApp" runat="server" OnClick="LinkSwitchApp_Click">Switch To DataBase2</asp:LinkButton>
该按钮的点击我想改变connection string
我的应用程序,即从DataBase1
开关DataBase2
。应用程序默认连接到DataBase1。
protected void LinkSwitchApp_Click(object sender, EventArgs e)
{
// Code to connect to different connection string
}
我有两个Connection Strings
在我Web.Config
文件:
<connectionStrings>
<add name="Default" connectionString="Data Source=Server; Initial Catalog=DataBase1; Integrated Security=true"
providerName="System.Data.SqlClient" />
<add name="Second" connectionString="Data Source=Server; Initial Catalog=DataBase2; Integrated Security=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
我的应用程序连接到DataBase1
(开始),当用户点击LinkButton
(文:切换到DATABASE2),程序丢失了与DataBase1
连接并获得连接到DataBase2
,并且应从当前的DataBase
即DataBase2
重新加载所有应用数据(甚至控制中的数据,如GridView
,Textbox
)。
现在,该LinkButton
文本将被更改为Switch To DataBase1
,当用户再次点击它,然后DataBase1
将被连接和应用程序将被重新加载。但是只有特定的用户,其他用户应该选择DataBase
。
目前,我在Global.asax
文件中提供connectionString
到我的应用程序(My DataBase Helper类)Application_Start
。像:
protected void Application_Start(object sender, EventArgs e)
{
DatabaseHelper.ConnectionString = WebConfigurationManager.ConnectionStrings["Default"].ConnectionString;
//Code to connect to Second ConnectionString(here or somewhere else based on condition)
}
我现在不为用户创建会话,但愿意创建如果需要。 (我试图在web.config
中动态地改变连接字符串,但是它会改变所有我不想要的用户)。请帮我实现这一点。
任何帮助,将不胜感激。先谢谢你...!!!
答
做这样的事情。
//DbHelper class
public static string AppConnectionString(){
if(Session["cnn"] != null)
return ConfigurationManager.ConnectionStrings["Second"].ConnectioonString;
return ConfigurationManager.ConnectionStrings["Default"].ConnectioonString;
}
//button handler
protected void LinkSwitchApp_Click(object sender, EventArgs e)
{
if(Session["cnn"] != null)
Session.Remove("cnn");
else
Session["cnn"] = true; //or whatever
}
//any time you connect to DB
var conn = new SqlClient.SqlConnection(DbHelper.AppConnectionString());
答
选项:
您可以使用cookies后,该按钮是点击
在您的按钮:
Protected void LinkButtonClick(Object sender,EventArgs e)
{
HttpCookie SetCookies = Request.Cookies["linkbutton"];
SetCookies ["linkbutton"] = "Button was click";
SetCookies .Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(SetCookies);
}
然后在你要连接的Database2每一个模块,
使用public string constr = String.Empty;
if(Request.Cookies["linkbutton"].ToString()=="Button was click")
{
constr = ConfigurationManager.ConnectionStrings["Second"].ToString()
}
else
{
constr = ConfigurationManager.ConnectionStrings["Default"].ToString()
}
就是这样的。
请记住您的cookies名称必须相同。
使用'会话'变量。这是最简单的方法。 –
@Alex Kudryashew谢谢,你能给我想法,我从来没有使用会话变量 – Preet