简体   繁体   English

Asp.net WebForms DropDownList-具有不同值和显示文本的控件(DataValueField / DataTextField)

[英]Asp.net WebForms DropDownList - controls with different values and displayed texts (DataValueField/DataTextField)

I have two entity classes - Users and Tasks. 我有两个实体类-用户和任务。 Every User has the following properties: UserId (int), Username (string), Password (string), FirstName (string), Lastname (string) 每个用户都具有以下属性: UserId (int), Username (字符串), Password (字符串), FirstName (字符串), Lastname (字符串)

and every Task, these: TaskId (int), Title (string), Description (string), EstimatedTime (int), CreatedOn (Datetime), CreatedBy (int), AssignedTo (int), Finished (bool) 和每一个任务,这些: 任务id(INT), 标题 (串), 说明 (串),EstimatedTime(INT),CreatedOn(日期时间),CreatedBy(INT),AssignedTo(INT), 完成 (布尔)

So CreatedBy and AssignedTo are actually UserIds - CreatedBy is the Id of the user, who created the task, and AssignedTo - the id of the one the task is for. 因此, CreatedByAssignedTo实际上是UserIds-CreatedBy是创建任务的用户的ID,而AssignedTo是任务所在的用户的ID。 I have a database where I use them - no problems there. 我有一个使用它们的数据库-那里没有问题。

In my WebForms Application I use a GridView to show the Tasks. 在我的WebForms应用程序中,我使用GridView来显示任务。 So I hide the TaskId and all the other properties are shown as columns in the GridView. 因此,我隐藏了TaskId,所有其他属性在GridView中显示为列。 But, the problem is, I don't want my users to see the values in CreatedBy and AssignedTo as ids(integers) - I want them to see the values as Usernames, so it would look like this: AssignedTo - "myUsername", and not like this: AssignedTo - 321. 但是,问题是,我不希望我的用户以id(integers)的形式看到CreatedBy和AssignedTo中的值-我希望他们将这些值视为用户名,所以看起来像这样:AssignedTo-“ myUsername”,而不是这样:AssignedTo-321。

This is my first problem, I don't know how to do that. 这是我的第一个问题,我不知道该怎么做。 As you will see in my code, the ItemTemplate is a Label, Bound to the property AssignedTo. 正如您将在我的代码中看到的那样,ItemTemplate是一个Label,绑定到属性AssignedTo。 How can I keep the value invisible and display the username instead? 如何保持该值不可见并显示用户名?

Second, as I log in as an admin, I want to be able to edit the Tasks. 其次,当我以管理员身份登录时,我希望能够编辑任务。 So I added these command fields to my GridView: 因此,我将以下命令字段添加到了GridView中:

<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />

I have a TaskRepository ans UserRepository that I use to access my database. 我有一个TaskRepository和UserRepository,用于访问数据库。 For example, the GridView is bound to a property in my TaskRepository that returns a list of all the tasks : 例如,GridView绑定到我的TaskRepository中的一个属性,该属性返回所有任务的列表:

TaskRepository taskRepo = new TaskRepository;
GridViewTasks.DataSource = taskRepo.GetAll();
GridViewTasks.DataBind();

Everything works perfectly. 一切正常。 And here is my AssignedTo ItemTemplate: 这是我的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>

So when I edit a task, I click "Edit" and I can change the values in the selected row in each column. 因此,当我编辑任务时,单击“编辑”,然后可以更改每一列中所选行的值。 But the problem, again, is with AssignedTo. 但是问题仍然出在AssignedTo。 As you can see from the code, when I edit it I see a DropDownList where insted of Ids, I have to choose from usernames. 从代码中可以看到,当我对其进行编辑时,我看到一个放置了ID的DropDownList,我必须从用户名中进行选择。 But the moment I try to save my changes, I get an object null reference exception.. I don't know why. 但是,当我尝试保存所做的更改时,我得到一个对象null引用异常。。我不知道为什么。 Here is my code: 这是我的代码:

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

Everything works with the other controls but when it gets to task.AssignedTo, I get the exception. 一切都与其他控件一起工作,但是当它进入task.AssignedTo时,我得到了异常。 Here is what I want to happen: When I click Edit, I want to see a DropDownList in the AssignedTo column with all my users usernames to choose from (so far, so good) and when I select a user and click Update, I want it to get the selected username value of assignedTo, knowing the userId it corresponds to and update my Task. 这是我要发生的事情:当我单击“编辑”时,我想在AssignedTo列中看到一个DropDownList,其中包含我所有用户的用户名供选择(到目前为止,很好),当我选择一个用户并单击“更新”时,我想要它获取选定的用户名值assignedTo,知道它对应的用户标识并更新我的任务。 Where do I go wrong? 我哪里出错了?

Sorry for the long post, I tried to be as thorough as possible and since I don't understand where the problem is, maybe I even missed something important (this is my first post). 很抱歉,对于冗长的帖子,我试图尽可能地做到透彻,并且由于我不明白问题出在哪里,也许我甚至错过了一些重要的事情(这是我的第一篇文章)。 Please help, because I've been stuck on this since forever. 请帮忙,因为我从一开始就坚持这样做。

For you first problem you can use an OnRowDataBound method to convert your ID to a username. 对于第一个问题,您可以使用OnRowDataBound方法将您的ID转换为用户名。 Essentially you get the ID from the row and get the name based on the ID. 本质上,您从行中获取ID,然后根据ID获得名称。

For example: 例如:

protected void Gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
       //get your control like in rowupdating
       //take the ID value and query against your user info to get the name
       // set the value
    }
}

For your second problem it might be that you need OnRowUpdated instead. 对于第二个问题,可能是您需要OnRowUpdated代替。 I don't have VS installed on this computer to try it out, so this is just a guess. 我没有在这台计算机上安装VS来进行尝试,所以这只是一个猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM