Vova Potapov Vova Potapov - 1 month ago 19
ASP.NET (C#) Question

Get text/value from textbox after value/text changed server side

I have a

FormView
with data(
DataSource
,
DataBind
) that I fill with
value='<%# Eval("Name") %>'
, but after I'm changing the text in
TextBox
and press update button I see the same value that before, I cant see new value that I have typed.

What I am missing here?

my html

<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />


Server side

protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}


public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}

Answer

In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:

HtmlInputText twt;

protected void Page_Load(object sender, EventArgs e)
{
      if (!IsPostBack)
      {
           using (DB_MikaDataContext data = new DB_MikaDataContext())
           { 
                MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
                MainFormTemplate.DataBind();
           }
      }
      else 
      {
           twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
      }           
}

protected void btn_Update_OnClick(object sender, EventArgs e)
{
     string text = twt.Value; // You will get the new value
}
Comments