【问题标题】:Changing Value to DataGrid cell将值更改为 DataGrid 单元格
【发布时间】:2013-05-01 16:56:24
【问题描述】:

我的代码隐藏中有一个设置数据网格的函数。我创建了一个新的空白列并将其添加到我的数据网格中,并且我想只为与对象 ID 匹配的一行添加一个值。出于某种原因,单元格不存储我设置的文本。有什么想法吗?

public void SetContacts(IEnumerable<User> contactList, User reqUser)
    {
        BoundColumn reqColumn = new BoundColumn();
        reqColumn.HeaderText = "";
        dgExistingContacts.Columns.Add(reqColumn);
        dgExistingContacts.DataSource = contactList;

        foreach (DataGridItem row in dgExistingContacts.Items)
        {
            if (row.Cells[0].Text == reqUser.id.ToString())
                row.Cells[6].Text = "Requestor";
        }
        dgExistingContacts.DataBind();

    }

如果有帮助,这是我的数据网格:

<asp:DataGrid runat="server" ID="dgExistingContacts" AutoGenerateColumns="false" CssClass="styledGray" HeaderStyle-CssClass="head" CellSpacing="1" CellPadding="4" GridLines="None" AlternatingItemStyle-CssClass="even" ItemStyle-CssClass="odd">
                    <Columns>
                        <asp:BoundColumn DataField="Id" Visible="false" />
                        <asp:BoundColumn DataField="Title" HeaderText="Role" />
                        <asp:BoundColumn DataField="LastName" HeaderText="Last Name" ItemStyle-Wrap="false" />
                        <asp:BoundColumn DataField="FirstName" HeaderText="First Name" ItemStyle-Wrap="false" />
                        <asp:BoundColumn DataField="Phone" HeaderText="Phone" DataFormatString="{0:(###) ###-####}" />
                        <asp:BoundColumn DataField="EmailAddress" HeaderText="Email" ItemStyle-Wrap="false" />
                    </Columns>
                </asp:DataGrid>

我觉得它应该很简单,但我不明白为什么它不具有约束力。

【问题讨论】:

    标签: c# asp.net datagrid


    【解决方案1】:

    我发现您必须在尝试更改内容之前绑定数据。我最终得到了这个:

    public void SetContacts(IEnumerable<User> contactList, User reqUser)
    {
        BoundColumn reqColumn = new BoundColumn();
        reqColumn.HeaderText = "";
        dgExistingContacts.Columns.Add(reqColumn);
        dgExistingContacts.DataSource = contactList;
        dgExistingContacts.DataBind();
        foreach (DataGridItem row in dgExistingContacts.Items)
        {
            if (row.Cells[0].Text == reqUser.id.ToString())
                row.Cells[6].Text = "Requestor";
        }
    }
    

    【讨论】:

      【解决方案2】:

      正如我所见,您正在向dgExistingContacts 添加一列,然后将contactList 分配为dgExistingContacts 的DataSource,这意味着您首先添加列,然后在此代码中将DaraGrid 重置为前DataSource:

          dgExistingContacts.Columns.Add(reqColumn);
          dgExistingContacts.DataSource = contactList;
      

      我认为当您将DataSource 分配给GridView 时,您在其中更改的任何内容都将被重置。所以也许通过从代码中删除dgExistingContacts.DataSource = contactList;,您的问题将得到解决。

      【讨论】:

        【解决方案3】:

        尝试处理GridView 的RowDataBound 事件并在那里添加值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-03-29
          • 2011-07-29
          • 2016-03-07
          • 2010-09-27
          • 2015-12-16
          相关资源
          最近更新 更多