我正在尝试将项目ID从Query String传递到ddb_projectList以使项目被选中并填充GridView但我的问题是当页面加载它时选择第一个追加Item。请注意,所选值仍为-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();
}
}
}
答案 0 :(得分: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
}