2012-10-31 172 views
0

我有一個GridView的按鈕,將所有行設置爲編輯模式(這是我想要的)。然而,我想知道是否有一種方法來創建一個按鈕,將更新整個gridview與我的更改。這是背後的代碼。Gridview更新按鈕

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" 
     onrowcommand="gvUsers_RowDataBound"> 
    <Columns> 


     <asp:TemplateField HeaderText="labelID" Visible="false"> 
      <ItemTemplate> 
       <asp:Label ID="ID" runat="server" Text='<%# Eval("id") %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 

     <asp:TemplateField HeaderText="First Name"> 
      <ItemTemplate> 
       <asp:Label ID="labelfirstname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' /> 
       <asp:TextBox ID="txtFirstName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' /> 
      </ItemTemplate> 
     </asp:TemplateField> 
     <asp:TemplateField HeaderText="Last Name"> 
      <ItemTemplate> 
       <asp:Label ID="labellastname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' /> 
       <asp:TextBox ID="txtLastName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' /> 

      </ItemTemplate> 
     </asp:TemplateField> 


    </Columns> 
    </asp:GridView> 


<asp:Button ID="Button1" runat="server" Text="Edit Mode" onclick="Button1_Click1" /> 
<asp:Button ID="Button2" runat="server" Text="View Mode" onclick="Button2_Click1" /> 

這裏是C#

private bool isEditMode = false; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      BindData(); 
     } 
    } 
    private void BindData() 
    { 

     string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True"; 
     SqlConnection myConnection = new SqlConnection(connectiongString); 
     SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname FROM Company", myConnection); 
     DataSet ds = new DataSet(); 
     ad.Fill(ds); 
     gvUsers.DataSource = ds; 
     gvUsers.DataBind(); 

    } 

    protected bool IsInEditMode 
    { 

     get { return this.isEditMode; } 

     set { this.isEditMode = value; } 

    } 

    protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e) 
    { 

    } 

    protected void Button1_Click1(object sender, EventArgs e) 
    { 
     isEditMode = true; 

     BindData(); 
    } 

    protected void Button2_Click1(object sender, EventArgs e) 
    { 

     isEditMode = false; 

     BindData(); 
    } 

預先感謝您!

回答

1

可以遍歷直通你行,得到的值在文本框的特定行

foreach (GridViewRow row in gvUsers.Rows) 
    { 
     TextBox txtFirstName = row.FindControl("txtFirstName") as TextBox; 
     TextBox txtLastName = row.FindControl("txtLastName") as TextBox; 

     if (txtFirstName.Text!="" && txtLastName.Text!="") 
     { 
      // do what you need with values 
     } 

    }