0

我正在尝试将项目 ID 从查询字符串传递给 ddb_projectList 以使项目被选中并填充 GridView 但我的问题是当页面加载时它选择了第一个附加项目。注意选择的值仍然 -1

谁能帮忙解决这个问题


代码:

 public partial class TasksInProjects : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //get loged in user id UserID from MembershipUser 
            MembershipUser memberUser = Membership.GetUser();
            string StrUserID = memberUser.ProviderUserKey.ToString();
            Guid userID = Guid.Parse(StrUserID);
            hf_userID.Value = userID.ToString();

            if (Request.QueryString["projectID"] == null)
            {


                //ddl_projects.SelectedValue = Request.QueryString["projectID"];

                if (ddl_projects.SelectedValue != "-1")
                {

                    Guid projectID = Guid.Parse(ddl_projects.SelectedValue);
                    gv_TaskListForUser.DataSource = Task.GetTasksInProjectForUser(userID, projectID);
                    gv_TaskListForUser.DataBind();
                }

            }
            else
            {

                //ddl_projects.Visible = false;
                //Guid projectID = Guid.Parse(Request.QueryString["projectID"]);
                //gv_TaskListForUser.DataSource = Task.GetTasksInProjectForUser(userID, projectID);
                //gv_TaskListForUser.DataBind();

                ddl_projects.SelectedItem.Value = Request.QueryString["projectID"];
                Guid projectID = Guid.Parse(ddl_projects.SelectedItem.Value.ToString());
                gv_TaskListForUser.DataSource = Task.GetTasksInProjectForUser(userID, projectID);
                gv_TaskListForUser.DataBind();
            }
        }

    }
4

1 回答 1

1

试试这个:

ddl_projects.ClearSelection();
ddl_projects.Items.FindByValue(Request.QueryString["projectID"]).Selected = true;

附带说明

我建议将其包装起来以防止发生错误。用户经常决定使用 URL。所以最好你做尽可能多的检查,以防他们决定摆弄!只是一个例子,因为验证完全取决于你想要实现的范围,但如果我是你,我至少会使用以下内容:

int projectID = 0;

// Check the query string is an integer
if (int.TryParse(Request.QueryString["projectID"], out projectID))
{
    // You could apply addition checks here, such as check that the project id is valid etc.
    ListItem projectItem = ddl_projects.Items.FindByValue(projectID.ToString());

    // if there is a project item with that value in the drop down list
    if (projectItem != null)
    {
        ddl_projects.ClearSelection();
        projectItem.Selected = true;
    }
}
else
{
    // do something, e.g. display friendly error message or whatever else is required
}
于 2012-06-21T14:43:42.553 回答