我有一个 Gridview,它正在从本地数据库中获取数据。已经设置了gridview,以便您可以编辑该行中的数据。但是,当您尝试编辑数据时,文本中会添加尾随空格。
因此,当编辑说像“Tom”这样的名字时,文本框将显示“Tom.........”(假设点是空格),这也是后端将收到的内容。
我似乎无法弄清楚为什么。代码如下,任何帮助表示赞赏。
<asp:GridView ID="gvActiveStudents" runat="server" OnRowDeleting="gvActiveStudents_RowDeleting" OnRowCancelingEdit="gvActiveStudents_RowCancelingEdit"
OnRowEditing="gvActiveStudents_RowEditing" OnRowUpdating="gvActiveStudents_RowUpdating" AutoGenerateEditButton="true" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CommandName="Delete" Text="Inactive" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="true" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
</Columns>
</asp:GridView>
C#
protected void gvActiveStudents_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvActiveStudents.EditIndex = -1;
getStudents();
}
protected void gvActiveStudents_RowEditing(object sender, GridViewEditEventArgs e)
{
gvActiveStudents.EditIndex = e.NewEditIndex;
getStudents();
}
解决方案:在 RowEditing 中修剪空格
string firstname = ((TextBox)gvActiveStudents.Rows[index].Cells[3].Controls[0]).Text.TrimEnd();
((TextBox)gvActiveStudents.Rows[index].Cells[3].Controls[0]).Text = firstname;
string lastname = ((TextBox)gvActiveStudents.Rows[index].Cells[4].Controls[0]).Text.TrimEnd();
((TextBox)gvActiveStudents.Rows[index].Cells[4].Controls[0]).Text = lastname;