1

根据下面的代码,在获取一些值(newrev,newreview)并放入变量后,我需要将它们放入标签中(“some text”+newrev)。但我有问题(newrev)在当前上下文中不存在。

Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";

protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
    _DataContext = new EDMSDataContext();

    var x = ddlProjectDocument.SelectedValue;

    var MaxRev = (from rev in _DataContext.tblTransmittalls
                  where rev.DocID.ToString() == ddlProjectDocument.SelectedValue
                  select  rev.REV).Max();

    if (MaxRev == null)
    {
        var newRev = 0;

    }

    else
    {

        var newRev = Convert.ToInt32(MaxRev) + 1;

    }

    var MaxReview = (from rev in _DataContext.tblFiles
                  where (rev.DocId.ToString()==ddlProjectDocument.SelectedValue)&&   
                        (rev.Rev.ToString()==MaxRev)
                  select rev.Review).Max();

    if (MaxReview == null)
    {
        var newReview = 1;
    }

    else
    {    
        var newReview = Convert.ToInt32(MaxReview) + 1;
    }

    Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";
}
4

4 回答 4

2

像这样定义newRevnewReview在函数的开头:

protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
    _DataContext = new EDMSDataContext();
    int newRev;
    int newReview;

然后,当您想使用它们时,而不是编写var newReview = ...(声明一个新变量)删除var... 例如:

if (MaxReview == null)
{
    newReview = 1;
}

区别: 声明的每个变量都有一个Scope,它决定了它对程序其余部分的可见性。在您的情况下, the仅在statementnewReview内部已知,因此当您尝试在外部引用它时,它不再存在。if

于 2013-02-19T14:57:48.007 回答
1

您需要在声明newRev之外if声明。

int newrev;
if(MaxRev == null)
    newRev = 0;
else
    newRev = Convert.ToInt32(MaxRev) + 1;
于 2013-02-19T14:56:45.557 回答
1

C# 不是 JavaScript,你应该少用“var”……你在里面定义你的 newRev

if (MaxRev == null)
{
    var newRev = 0;
}

在这里定义

protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
     _DataContext = new EDMSDataContext();
     var newRev = 0;
     ....
}
于 2013-02-19T14:58:01.970 回答
1

这是因为您在各种 if 语句中声明 newRev,在外部级别声明它:

int newRev;
if (MaxRev == null)
{
    newRev = 0;

}
于 2013-02-19T14:58:49.830 回答