[英]Set SQL Server name in connection string not working
I have Formselectserver
where get the name of a SQL Server from a combobox. 我有Formselectserver
,从组合框中获取SQL Server的名称。 Also I have form2
where is main form. 我也有form2
在哪里是主要形式。
I send combobox.selectedvalue
to connection string in form2 but that does not work. 我将combobox.selectedvalue
发送到form2中的连接字符串,但这不起作用。
I want user select one SQL Server in network and connect to it. 我希望用户在网络中选择一个SQL Server并连接到它。
Formselectserver objfrmserver = new Formselectserver();
private const string strconnection =
@"server='" + objfrmserver.cmbshowallsqlserver.SelectedValue +
"';database = anfd; Integrated Security = SSPI";
The error is: 错误是:
An object reference is required for the non-static field, method, or property 'exportdatafromholoo.Form1.objfrmserver' 非静态字段,方法或属性'exportdatafromholoo.Form1.objfrmserver'需要对象引用
Two things are wrong: 有两件事是错误的:
const
. 只需删除const
。 objfrmserver
also a member of that same class? 您的objfrmserver
还是该类的成员吗? You cannot initialize fields in the same class with each other. 您不能互相初始化同一类中的字段。 Move your initialization to the constructor. 将初始化移到构造函数。 Try this: 尝试这个:
public void MyMethod()
{
Formselectserver objfrmserver = new Formselectserver();
string strconnection = @"server='" + objfrmserver.cmbshowallsqlserver.SelectedValue + "';database = anfd; Integrated Security = SSPI";
}
A const
is a compile-time constant, so can only involve things that are known at compile-time - basically, literals. const
是一个编译时常量,因此只能包含在编译时已知的内容-基本上是文字。
objfrmserver
is an instance (per-object) field that is a reference to another object, at runtime. objfrmserver
是实例(按对象)字段,在运行时是对另一个对象的引用。 This will not work. 这是行不通的。 So basically, your strconnection
cannot be a const
. 因此,基本上,您的strconnection
不能是const
。 I suspect there's also not much purpose in it being a field. 我怀疑这是一个领域也没有太多目的。 But as a variable it might make sense, ie 但作为变量可能是有道理的,即
public void Connect() {
var strconnection = @"server='" + objfrmserver.cmbshowallsqlserver.SelectedValue + "';database = anfd; Integrated Security = SS=PI";
var conn = new SqlConnection(strconnection);
conn.Open();
// etc...
}
You might also want to look at SqlConnectionStringBuilder
, to avoid having to know the escaping rules associated with server-names. 您可能还希望查看SqlConnectionStringBuilder
,以避免必须知道与服务器名称关联的转义规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.