变量未声明或从未赋值

lyb_abiandbel 2005-07-25 02:36:04
ConnectServer cs=new ConnectServer();//自己写的类
this.sqlConnection1.ConnectionString=cs.ConnectString;

调用类时出现“变量cs未声明或从未赋值”,

声明private ConnectServer cs,问题依旧,private ConnectServer cs=null,问题依旧。

程序可以编译通过,但是有错总是不舒服啊!
哪位碰到过?怎么解决?郁闷.....

...全文
2240 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuranccc2003 2005-07-26
  • 打赏
  • 举报
回复
多谢指教
okyzx 2005-07-25
  • 打赏
  • 举报
回复
是呀,写在Form_load,跟写在InitializeComponent没区别的
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
不是构造函数的问题,构造函数是空的,没有任何改动。

还是 MyLf(不睡觉的鱼) 说的对啊!

写在InitializeComponent()里面应该没有错的,关键是InitializeComponent()在加载页面时也要执行的,而Form_Load却不会执行(只有F5时才执行),显示的时候没有编译,自然会有那个错误

这就是为什么编译的时候没有错的原因。不知道各位能不能懂我说什么啊!

哈哈!搞定,还是要靠自己啊!

散分!
wxwx110 2005-07-25
  • 打赏
  • 举报
回复
private ConnectServer cs=null
这样写当然错了哦

检查一下ConnectServer的构造函
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
看来只能写在Form_load里面了。
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
to: MyLf(不睡觉的鱼)

你说的很对,InitializeComponent()手工加入的代码很容易丢失,不知道这个有没有解决的方法?
但是我的确遇到要在窗体初始化时加入代码,怎么办?可以放在Form_load中吗?
hnhl 2005-07-25
  • 打赏
  • 举报
回复
试试
把这两句写到Form_Load事件里应该就没问题了
this.c=new Class1();
this.sqlConnection1.ConnectionString=c.s;
MyLf 2005-07-25
  • 打赏
  • 举报
回复
理论上说,写在InitializeComponent()没有问题,但不推荐。因为它是窗体设计器自动产生的,如果界面修改了,InitializeComponent()里的代码会重新构造一遍。你手工加入的代码可能会丢失。

hnhl 2005-07-25
  • 打赏
  • 举报
回复
把Class1 源码贴出来
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
写到别的函数里面没有问题啊,

public class Form1 : System.Windows.Forms.Form
{
private Class1 c;
private System.Data.SqlClient.SqlConnection sqlConnection1;
...........

public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{

this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();


.........

this.c=new Class1(); //写在这里有问题!
this.sqlConnection1.ConnectionString=c.s;
}

public void test()
{
this.c=new Class1(); //写在这里没有问题!
this.sqlConnection1.ConnectionString=c.s;
}
}

是否是InitializeComponent()的问题?不能写这里?
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
我写成这样,还是一样啊!

public class Form1 : System.Windows.Forms.Form
{
private Class1 c;
private System.Data.SqlClient.SqlConnection sqlConnection1;
...........

public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.c=new Class1();
this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();


.........
this.sqlConnection1.ConnectionString=c.s;
}





}


MyLf 2005-07-25
  • 打赏
  • 举报
回复
ConnectServer的构造函数是不是有问题呢?以至于实例不成功
lyb_abiandbel 2005-07-25
  • 打赏
  • 举报
回复
private ConnectServer cs=new ConnectServer(),问题依旧。

110,559

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧