【问题标题】:Variable from another void来自另一个 void 的变量
【发布时间】:2014-08-24 16:46:16
【问题描述】:

我是一个新手程序员 (c#),我卡住了。我不知道为什么编译器看不到另一个 void 的变量。大约一周前在另一个程序中它工作了,现在不想了。我正在寻找类似的问题,但我没有找到。

public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
    int index;
    if (ev.CommandName == "Update")
    {
       index = Convert.ToInt32(ev.CommandArgument);
    }
}

protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{   
    String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);

    con.Open();
    SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
    cmd.ExecuteNonQuery();
    con.Close();
}

我想要 index 变量到 SqlCommand 对象。

顺便说一句。这是好代码吗?它会起作用吗?我想在gridview中更新数据(行)后将变量'Permit'插入到单元格[LastModified]中。

这似乎不能正常工作:(我的意思是,变量“索引”现在很好,但代码只是坏了。

【问题讨论】:

标签: c# variables void


【解决方案1】:

在 void 之外声明您的变量,以便您可以从所有成员访问它。 正如你所拥有的,它只对Gridcommandevent可见

int index;
public void Gridcommandevent(object sender, GridViewCommandEventArgs ev)
{
    if (ev.CommandName == "Update")
    {
       index = Convert.ToInt32(ev.CommandArgument);
    }
}

protected void GridView3_RowCommand(object sender, GridViewUpdateEventArgs e)
{   
    String strConnString = ConfigurationManager.ConnectionStrings["DGCodLocConnection"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);

        con.Open();
        SqlCommand cmd = new SqlCommand("UPDATE Parts SET [LastModified] = '" + Permit + "' WHERE PartsID = '" + index + "'", con);
        cmd.ExecuteNonQuery();
        con.Close();
}

按照Andreas Niedermair的建议,既然你说你是新手程序员,你应该看看这个MSDN Article

【讨论】:

  • no no no ... OP 显然是一个绝对的初学者。操作员问的是“为什么”而不是“如何”......
  • @AndreasNiedermair 看看他问题的最后一行。他想要一种访问变量的方法。
  • ...并且(s)他不知道为什么它不能通过其他方法访问...鉴于您的技能水平,您至少应该提及 范围
  • @AndreasNiedermair 既然你已经在问题的评论中提到了这一点,你还好吗,如果我在我的答案中使用链接?对于什么是值得的,你是对的,我应该更深入地了解变量可见性。
  • 好吧。我的错。我只是长时间地看这段代码。感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
相关资源
最近更新 更多