1

我在带有文本框的 Gridview 中有一个 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;



    }


}

}

4

1 回答 1

1

问题出在UserControl代码中。无论是否回发,您每次都将文本设置为Name属性的值。

你需要这样做:

if(!IsPostback)
 txt_name.Text = Name;
于 2012-09-02T15:21:33.943 回答