2013-04-23 49 views
0

我有一个Gridview从本地数据库提供数据。 gridview已经设置好,所以你可以编辑该行中的数据。但是,当您尝试编辑数据时,会在文本中添加尾随空格。ASP .NET Gridview编辑文本框添加空格到数据的末尾

所以当编辑说出一个像“汤姆”这样的名字时,文本框会显示“汤姆.........”(假设点是空格),这就是后端会收到的。

我似乎无法弄清楚为什么。代码如下,任何帮助表示赞赏。

<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; 

回答

0

修剪空间在上之前将其保存到数据库编辑的值的OnRowUpdating方法调用Trim()

+0

是的,这是我已经做了,但我想在此之前删除空格,他们不应该首先在文本框中出现。 – SikhWarrior 2013-04-23 02:59:07

+0

他们在db吗?你也可以去掉RowEditing事件。 – 2013-04-23 03:02:15

+0

空格不在数据库中。当数据加载并且空间仍然显示时,我调用trim。我将如何去修剪RowEditing? – SikhWarrior 2013-04-23 03:04:29

0

如果数据库中的数据类型是一个固定的字符串,比如一个nchar,那么您应该在您返回它时随时使用RTRIM(),因为SQL Server会用空白填充字符串。

名字用的值存储为NCHAR(10)在数据库 '汤姆'

select FirstName from people returns 'Tom '

select RTRIM(FirstName) from people returns 'Tom'

此外,如果通过名字任何约束力记得别名列

select RTRIM(FirstName) as FirstName from people