Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textbox.text always returning empty string instead of user's entered text

Tags:

asp.net

I am very surprised to see last night my code was working fine and the next day suddenly my textbox.text always have empty string..
My code is:

 Name of Event* :

    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />

Code behind:

protected void Page_Load(object sender, EventArgs e) {
} 

protected void create_Click(object sender, EventArgs e) {

    if (!object.Equals(Session["UserLoginId"], null)) { 

        int mid = 0; 
        int cid = 0; 
        bool valid = true;

        if (this.TextBox1.Text == "") {

            error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>"; 

        }

        else { 
            .... // database insert .... 
        }

I am always ending up with an error.text value.

Why?

like image 835
gitesh tyagi Avatar asked Apr 17 '11 11:04

gitesh tyagi


3 Answers

Had a similar problem with text boxes getting cleared on adding a new row. It was the issue of the page reloading when the add button was clicked.

Fixed the issue by adding:

Sub Page_Load
  If Not IsPostBack Then 
    BindGrid()
  End If
End Sub

Per Microsoft's documentation http://msdn.microsoft.com/en-us/library/aa478966.aspx.

like image 123
user1131039 Avatar answered Oct 31 '22 16:10

user1131039


Kinda mentioned but you should make sure your checking your that Post_Back event is not clearing your textbox. It would by default. Try something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        {
            if (this.TextBox1.Text == "")
            {
                error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
            }
        else
        {
            //.....
        }
    }
}
like image 45
darren Avatar answered Oct 31 '22 16:10

darren


I had a similar problem. I had a textarea feeding data to a database on postback. I also designed the page to populate the textarea from the same database field. The reason it failed was because I forgot to put my reload logic inside an if(!IsPostPack) {} block. When a post back occurs the page load event gets fired again and my reload logic blanked the textarea before I could record the initial value.

like image 39
Daniel D. Avatar answered Oct 31 '22 17:10

Daniel D.