【发布时间】:2015-02-07 12:54:27
【问题描述】:
我有两个实体类 - 用户和任务。每个用户都有以下属性: UserId(int), 用户名(string), 密码(string), FirstName(string), 姓氏(字符串)
以及每个任务,这些: TaskId(int), Title(string), Description(string), EstimatedTime(int), CreatedOn(日期时间),CreatedBy(int),AssignedTo(int),Finished(bool)
所以 CreatedBy 和 AssignedTo 实际上是 UserIds - CreatedBy 是创建任务的用户的 ID,而 AssignedTo - 任务所针对的用户的 ID .我有一个使用它们的数据库-那里没有问题。
在我的 WebForms 应用程序中,我使用 GridView 来显示任务。所以我隐藏了 TaskId,所有其他属性都显示为 GridView 中的列。但是,问题是,我不希望我的用户将 CreatedBy 和 AssignedTo 中的值视为 ids(integers) - 我希望他们将值视为用户名,所以它看起来像这样: 分配给 - “我的用户名”, 而不是这样: 分配给 - 321。
这是我的第一个问题,我不知道该怎么做。正如您将在我的代码中看到的,ItemTemplate 是一个标签,绑定到属性 AssignedTo。如何保持值不可见并改为显示用户名?
其次,当我以管理员身份登录时,我希望能够编辑任务。所以我将这些命令字段添加到我的 GridView 中:
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
我有一个 TaskRepository 和 UserRepository 用于访问我的数据库。例如,GridView 绑定到我的 TaskRepository 中的一个属性,该属性返回所有任务的列表:
TaskRepository taskRepo = new TaskRepository;
GridViewTasks.DataSource = taskRepo.GetAll();
GridViewTasks.DataBind();
一切都很完美。 这是我的 AssignedTo ItemTemplate:
<asp:TemplateField HeaderText="Assigned to">
<EditItemTemplate>
<asp:DropDownList ID="editAssignedTo" runat="server" DataTextField="Username" DataValueField="UserId"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbAssignedTo" runat="server" Text='<%#Bind("AssignedTo")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
因此,当我编辑任务时,我单击“编辑”,我可以更改每一列中所选行中的值。但问题又出在 AssignedTo 上。正如您从代码中看到的那样,当我编辑它时,我看到一个 DropDownList 插入了 Id,我必须从用户名中进行选择。但是当我尝试保存我的更改时,我得到一个对象空引用异常。我不知道为什么。这是我的代码:
protected void GridViewTasks_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow selectedRow = GridViewTasks.Rows[e.RowIndex];
Tasks task = new Tasks();
task.TaskId = (int)GridViewTasks.DataKeys[e.RowIndex].Value;
TextBox title = (TextBox)selectedRow.FindControl("tbTitle");
task.Title = title.Text;
TextBox description = (TextBox)selectedRow.FindControl("tbDescription");
task.Description = description.Text;
Label createdOn = (Label)selectedRow.FindControl("lblCreatedOn");
task.CreatedOn = DateTime.Parse(createdOn.Text);
Label createdBy = (Label)selectedRow.FindControl("lblCreatedBy");
task.CreatedBy = int.Parse(createdBy.Text);
TextBox estimTime = (TextBox)selectedRow.FindControl("tbEstimTime");
task.EstimatedTime = int.Parse(estimTime.Text);
DropDownList assignedTo = (DropDownList)selectedRow.FindControl("editAssignedTo");
task.AssignedTo = int.Parse(assignedTo.SelectedItem.Value);
Label lblFinished = (Label)selectedRow.FindControl("lblFinished");
task.Finished = bool.Parse(lblFinished.Text);
taskRepo.Save(task);
BindDataToGridView();
}
一切都与其他控件一起工作,但是当它到达 task.AssignedTo 时,我得到了异常。这是我想要发生的事情:当我单击编辑时,我希望在 AssignedTo 列中看到一个 DropDownList,其中包含可供选择的所有用户用户名(到目前为止,非常好),当我选择一个用户并单击更新时,我想要它获取选定的用户名值assignedTo,知道它对应的userId并更新我的任务。我哪里错了?
抱歉,这篇文章太长了,我试图尽可能详尽,因为我不明白问题出在哪里,也许我什至错过了一些重要的事情(这是我的第一篇文章)。请帮忙,因为我一直坚持这一点。
【问题讨论】:
标签: c# asp.net gridview webforms