简体   繁体   English

使用未分配的局部变量

[英]Use of Unassigned local variable

I encountered an error. 我遇到一个错误。 Despite declaring the variables (failturetext and userName) errors still appear. 尽管声明了变量(failturetext和userName),仍然出现错误。 Can anyone please help me? 谁能帮帮我吗?

- Use of Unassigned local variable "FailureText" 
- Use of Unassigned local variable "UserName"


protected void Login1_LoginError(object sender, System.EventArgs e)
{
    TextBox FailureText;
    TextBox UserName; 

    //There was a problem logging in the user
    //See if this user exists in the database
    MembershipUser userInfo = Membership.GetUser(UserName.Text); // errors appear here
    if (userInfo == null)
    {
        //The user entered an invalid username...
        //error appear here ( failuretext.text) 
        FailureText.Text = "There is no user in the database with the username " + UserName.Text;  
    }

Thanks (: 谢谢 (:

You've declared the variables, but you haven't assigned anything to them before you are attempting to reference their properties. 您已经声明了变量,但是在尝试引用它们的属性之前尚未给它们分配任何内容。 That's the origin of the messages. 这就是消息的来源。 You've got bigger problems, though, because those represent UI controls and it's highly unlikely that they should be local variables in your function. 但是,您遇到了更大的问题,因为这些问题代表UI控件,并且它们不太可能成为函数中的局部变量。 They probably ought to belong to the page (or form) rather than be declared locally. 它们可能应该属于页面(或表单),而不是在本地声明。

Regarding the compiler message - look at this link 关于编译器消息-查看此链接

 TextBox FailureText; - you declared a variable, but it is not initialized. you might set it to null / a value / default() - but you must initialize it
 TextBox UserName; - the same

when you call UserName.Text - the compiler alerts for the uninitialized UserName 当您调用UserName.Text时-编译器将提醒您未初始化的UserName

If you wish to keep the same convention as you have at the moment, then to solve the issue of it failing compilation you want to assign the two variables a null value first before you try to reference them. 如果您希望保持与目前相同的约定,那么要解决编译失败的问题,您需要在尝试引用它们之前先为两个变量分配一个空值。

Like so: 像这样:

TextBox FailureText = null;
TextBox UserName = null;

If you do this, you might need to check on whether they are still null when you try and assign the properties of these objects. 如果这样做,在尝试分配这些对象的属性时,可能需要检查它们是否仍然为null。

As people above have stated, you should not be doing it this way as UI controls should always be global to the form itself. 如上述人士所述,您不应以这种方式进行操作,因为UI控件应始终对表单本身是全局的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM