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

时间:2014-06-02 13:47:15

标签: c# code-behind

我这里有一小段代码:

    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。

请假设我是一个n00b,因为我非常喜欢,并且在你的答案中要彻底。太多的技术术语会让我感到困惑。 :O)

2 个答案:

答案 0 :(得分:4)

strSQL2未在adapter2范围内定义,请在同一范围内声明:

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

答案 1 :(得分:1)

试试这个:

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

               ...
    }