名称在当前上下文中不存在"c#代码隐藏错误

本文关键字:quot 代码 错误 隐藏 不存在 上下文 | 更新日期: 2023-09-27 18:06:10

这里有一小段代码:

    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);
               ...
    }

所以,我要做的是改变查询,使它填充下拉列表与一切,或只有适当的角色为该函数。当我写到:

                SqlDataAdapter adapter2 = new SqlDataAdapter(strSQL2, con);

它告诉我当前上下文中不存在strSQL。

请假设我是一个菜鸟,因为我确实是,并且在你的回答中要彻底。太多的专业术语会把我弄糊涂。: o)

名称在当前上下文中不存在"c#代码隐藏错误

strSQL2adapter2的作用域中没有定义,它们在同一个作用域中声明:

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);
               ...
    }