我在带有文本框的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;
}
}
}
}
UserControl代码:
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;
}
}
}
答案 0 :(得分:1)
问题出在UserControl
代码中。您每次都设置文本,回发与否,是Name
属性的值。
你需要这样做:
if(!IsPostback)
txt_name.Text = Name;