2012-09-02 34 views
1

我有一個帶有文本框的GridView中的UserControl。文本框由數據庫調用填充,然後可以由用戶編輯以保存另一個值。但是當我試圖保存另一個價值時,它就是沒有用的。下面的代碼:UserControl在回發後不保存值

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      string sql; 
      sql = "select lname from clients order by lname"; 
      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString()); 

      DataTable dt = new DataTable(); 
      SqlCommand cmd = new SqlCommand(sql, conn); 

      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      da.Fill(dt); 

      GridView1.DataSource = dt; 
      GridView1.DataBind(); 
     } 


    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     UserControl uc; 
     TextBox tb; 
     string name; 

     foreach (GridViewRow row in GridView1.Rows) 
     { 


      uc = (UserControl)row.FindControl("UserInfo1"); 
      tb = (TextBox)uc.FindControl("txt_name"); 
      name = tb.Text; 

     } 


    } 



} 

}

用戶控件代碼:

public partial class UserInfo : System.Web.UI.UserControl 
{ 

    public string Name {get;set;} 

    protected void Page_Load(object sender, EventArgs e) 
    { 

     txt_name.Text = Name; 


    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 

     string name; 

     name = this.txt_name.Text; 



    } 


} 

}

回答

1

的問題是在UserControl代碼。您每次都將文本設置爲回發或不回傳,即爲Name屬性的值。

你需要做這個:

if(!IsPostback) 
txt_name.Text = Name; 
+0

每一個新手似乎擊中發現這個錯誤的相同的模式... :) – deostroll

+0

非常感謝你...我得到它的工作。 –