2013-11-04 186 views
1

我有规则的asp.net gridview,我想在每行中启用editmode,也没有editbutton(如Excel网格)。 编辑的数据我想通过点击网格外的“发布”按钮(整个网格的一个按钮)保存到我的数据库。 我怎样才能达到它?Asp.net gridview编辑没有编辑按钮

回答

2

要做到这一点,你将不得不使用的ItemTemplate与他们中的文本框为控制每列..

ASP

<asp:TemplateField HeaderText="Heading Title" SortExpression="Heading Title"> 
        <ItemTemplate> 
         <asp:TextBox ID="tbTextbox" runat="server" Width="65px" Text='<%# Bind("ColumnNameYouWantToView") %>'></asp:TextBox>        
        </ItemTemplate> 
</asp:TemplateField> 

之后设置正确,你将需要发布按钮。您可以将其放入网格或网格外。我使用两者,但这里是网格内的一个页脚。

ASP

<asp:TemplateField> 
     <ItemTemplate> 
      <asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" Width="40px" /> 
     </ItemTemplate> 
     <FooterTemplate> 
      <asp:Button ValidationGroup="UPDATE" ID="btnUpdate" OnClick="btnUpdate_Click" runat="server" Text="Update" Width="50px"></asp:Button> 
     </FooterTemplate> 
     <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" /> 
</asp:TemplateField> 

到目前为止,最适合您的按钮点击使用foreach语句是我已经找到。这个想法的最大缺陷是它会更新每一行。它可以工作,但是如果您一次只更改一行,则会更新所有这些行。我将我的寻呼机设置为10,因此总是更新10行(除非您只是搜索单个记录并更新它,只更新单个记录)。

代码隐藏C#

protected void btnUpdate_Click(object sender, EventArgs e) 
     { 
      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString); 
      conn.Open(); 

      //finds the controls within the gridview and updates them 
      foreach (GridViewRow gvr in gvGridViewName.Rows) 
      { 
       string ID = (gvr.FindControl("lblId") as Label).Text.Trim();//finds the control in the gridview 
       string anotherControl = ((TextBox)gvr.FindControl("tbTextBox")).Text.Trim();//finds the textbox in the gridview 

       //Your update or insert statements 


     } 

这是我要做的事。你也可以看看Real World Grids,但我没有太多运气,因为如果一个文本框是空的,我总会得到一个错误。然而,这个假设是“聪明的”,足以更新已更改的行,但再次,我没有这么做的好运气。希望这可以帮助!