&引用;该名称在当前上下文中不存在;C#代码隐藏错误

&引用;该名称在当前上下文中不存在;C#代码隐藏错误,c#,code-behind,C#,Code Behind,我这里有一小段代码: private void cboFunction_SelectedIndexChanged() { using (SqlConnection con = new SqlConnection(str2)) { try { int FunID = Convert.ToInt32(cboFunction.SelectedValue);

我这里有一小段代码:

    private void cboFunction_SelectedIndexChanged()
    {
        using (SqlConnection con = new SqlConnection(str2))
        {

            try
            {
                int FunID = Convert.ToInt32(cboFunction.SelectedValue);
                if (FunID != 0)
                {
                    string strSQL2 = "Select [Role_ID], [Role] from [MOS_Role] where [Function_ID] = " + FunID + "";
                }
                else
                {
                    string strSQL2 = "Select [Role_ID], [Role] from [MOS_Role]";
                }


                SqlDataAdapter adapter2 = new SqlDataAdapter(strSQL2, con);
                DataSet DDLRoles = new DataSet();
                adapter2.Fill(DDLRoles);

               ...
    }
所以,我要做的是更改查询,使其要么用所有内容填充dropdownlist,要么只填充函数的适当角色。当我排队时:

                SqlDataAdapter adapter2 = new SqlDataAdapter(strSQL2, con);
它告诉我strSQL在当前上下文中不存在


请假设我是n00b,因为我基本上是n00b,请仔细回答。太多的技术术语会把我弄糊涂o)
strSQL2
未在
适配器2
的范围内定义,请在同一范围内声明它们:

private void cboFunction_SelectedIndexChanged()
{
    using (SqlConnection con = new SqlConnection(str2))
    {

        try
        {
            int FunID = Convert.ToInt32(cboFunction.SelectedValue);
            string strSQL2;
            if (FunID != 0)
            {
                strSQL2 = "Select [Role_ID], [Role] from [MOS_Role] where [Function_ID] = " + FunID + "";
            }
            else
            {
                strSQL2 = "Select [Role_ID], [Role] from [MOS_Role]";
            }


            SqlDataAdapter adapter2 = new SqlDataAdapter(strSQL2, con);
            DataSet DDLRoles = new DataSet();
            adapter2.Fill(DDLRoles);
试试这个:

private void cboFunction_SelectedIndexChanged()
    {
        using (SqlConnection con = new SqlConnection(str2))
        {
            string strSQL2= string.empty;

            try
            {
                int FunID = Convert.ToInt32(cboFunction.SelectedValue);
                if (FunID != 0)
                {
                    strSQL2 = "Select [Role_ID], [Role] from [MOS_Role] where [Function_ID] = " + FunID + "";
                }
                else
                {
                    strSQL2 = "Select [Role_ID], [Role] from [MOS_Role]";
                }


                SqlDataAdapter adapter2 = new SqlDataAdapter(strSQL2, con);
                DataSet DDLRoles = new DataSet();
                adapter2.Fill(DDLRoles);

               ...
    }

您需要在
if/else
块之外声明
strSQL2
。您必须了解变量寿命。基本上,如果它是在一个特定的块中声明的,那么它将只在这个块中可用。因此,正如上面评论中所建议的,
strSQL2
必须在同样使用它的块中声明,即在if/else语句之前。您可以声明
string strSQL2=string.Empty
。而不是在if块中指定特定值。