【问题标题】:Update GridView Column after databinding?数据绑定后更新 GridView 列?
【发布时间】:2017-07-15 18:28:53
【问题描述】:

我可以在数据绑定后更新 gridview 列的内容吗? SQL 列是一个全名,我需要将其显示为姓氏,名字,而不是名字姓氏,就像现在一样。我知道我可以在 sql 中执行此操作,但似乎会有点痛苦(SQL: parse the first, middle and last name from a fullname field)。我只是想知道是否有更简单的方法来做到这一点。

谢谢

好的,我想通了……抱歉。如果其他人需要这个,我添加了一个OnRowDataBound="MailingList_RowDataBound" 事件,在该事件处理程序中,我将使用以下代码(修改为解析名称):

public void MailingList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // Required to ignore the header/footer.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //Get the Person's Name
            string name = e.Row.Cells[0].Text;
            //Add your JavaScript onClick event link.
            e.Row.Attributes.Add("onClick", "LookupEmail('" + name + "')");
            e.Row.Cells[0].Text = "Test";
        }
    }

将“测试”更改为正确的值。

【问题讨论】:

    标签: c# asp.net data-binding


    【解决方案1】:

    使用项目模板

                <asp:GridView ID="tset" runat="server">
                   <Columns>
                      <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                           <asp:Label ID="label1" runat="server"  Text='<%#GetFormattedName(Eval("full_name")%>'></asp:Label>
                        </ItemTemplate>
                      </asp:TemplateField>
                   </Columns>
                </asp:GridView>
    

    并在后面的代码中编写 GetFormattedName 方法以根据需要返回字符串,

        protected string GetFormattedName(string fullName)
        {
              // you can split full name here and swap first name, last name
              // depending on how you store it in DB 
        }
    

    【讨论】:

      【解决方案2】:
      <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
          <span>
             <%# Eval("FullName").Split(' ')[0]%>
          </span>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Surname">
        <ItemTemplate>
          <span>
             <%# Eval("FullName").Split(' ')[1]%>
          </span>
         </ItemTemplate>
      </asp:TemplateField>
      

      这应该可以解决您的问题。假设您的数据库中的列名是 FullName 并且名字和姓氏用空格分隔,您可以将它们拆分并将每个值绑定到 GridView 中的不同列。

      【讨论】:

      • 如果您希望名称仍然在一个列中,您仍然可以这样做,只需将它们组合在一起 ""
      猜你喜欢
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      相关资源
      最近更新 更多