2013-11-04 185 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,但我沒有太多運氣,因爲如果一個文本框是空的,我總會得到一個錯誤。然而,這個假設是「聰明的」,足以更新已更改的行,但再次,我沒有這麼做的好運氣。希望這可以幫助!