DateTime变量超出范围

时间:2014-01-07 20:06:18

标签: c# code-behind

我在代码隐藏中得到了这段代码:

while (DT1.Read())
{
  //Read the record into an "array", so you can find the SProc and View names
  int MyRptID = Convert.ToInt32(DT1[0]);
  string MyRptName = DT1[1].ToString();
  string MyRptSproc = DT1[2].ToString();
  string MySQLView = DT1[3].ToString();

  if (string.IsNullOrWhiteSpace(this.txtStartDate.Text))
  {
     DateTime MyStDate = Convert.ToDateTime(this.txtStartDate.Text);
  }

  if (MyStDate != null)
  {
    cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = txtStartDate.Text;
  }

MyStDate用红色加下划线,当我将鼠标悬停在它上面时,我得到一个弹出窗口,上面写着“当前上下文中不存在名称'MyStDate'。”谁能告诉我为什么会这样?它是否与括号外的事实有关?如果是这样,我怎样才能让它发挥作用?

5 个答案:

答案 0 :(得分:3)

MyStDate的范围是if条件。变量在其范围之外不可见,因此您需要在MyStDate之外声明if

答案 1 :(得分:2)

您需要在if语句之前声明MyStDate。这就是它超出范围的原因。

while (DT1.Read())
{
    //Read the record into an "array", so you can find the SProc and View names
    int MyRptID = Convert.ToInt32(DT1[0]);
    string MyRptName = DT1[1].ToString();
    string MyRptSproc = DT1[2].ToString();
    string MySQLView = DT1[3].ToString();
    DateTime MyStDate;
    if (string.IsNullOrWhiteSpace(this.txtStartDate.Text))
    {
        MyStDate = Convert.ToDateTime(this.txtStartDate.Text);
    }

    if (MyStDate != null)
    {
        cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = txtStartDate.Text;
    }
}

答案 2 :(得分:1)

您在DateTime MyStDate块中定义if,因此在下一个if块中无法访问它(它超出范围)。

您需要在第一个if块中定义外部变量,以便稍后可以在方法中访问。

DateTime myStDate;

if (String.IsNullOrWhiteSpace(this.txtStartDate.Text))
    myStDate = Convert.ToDateTime(this.txtStartDate.Text);

if (myStDate != null)
    cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = myStDate;

实际上,您的代码看起来有些问题。

试试这个,而不是你现在得到的东西:

if (!String.IsNullOrWhiteSpace(txtStartDate.Text))
{
    DateTime myStDate;
    if (DateTime.TryParse("txtStartDate.Text", out myStDate))
        cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = myStDate;
}

答案 3 :(得分:0)

请改为:

DateTime MyStDate;
if (string.IsNullOrWhiteSpace(this.txtStartDate.Text))
{
     MyStDate = Convert.ToDateTime(this.txtStartDate.Text);
}

答案 4 :(得分:0)

您需要在if语句之外创建MyStDate的实例。 MyStDate对于声明范围之外的任何内容都不可见。

DateTime MyStDate = null;

if (string.IsNullOrWhiteSpace(this.txtStartDate.Text))
    MyStDate = Convert.ToDateTime(this.txtStartDate.Text);

if(MyStDate != null)
    cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = MyStDate;