开发者

Problems updating a textBox ASP.NET

开发者 https://www.devze.com 2023-01-02 02:46 出处:网络
I\'m starting in asp.net and am having some problems that I do not understand. The problem is this, I am building a site for news. Every news has a title and body. I have a page where I can insert new

I'm starting in asp.net and am having some problems that I do not understand. The problem is this, I am building a site for news. Every news has a title and body. I have a page where I can insert news, this page uses a textbox for each of the fields (title and body), after clicking the submit button everything goes ok and saves the values in the database. And o have another page where I can read the news, I use labels for eac开发者_高级运维h of the camps, these labels are defined in the Page_Load. Now I'm having problems on the page where I can edit the news. I am loading two textboxes (title and body) in the Page_Load, so far so good, but then when I change the text and I click the submit button, it ignores the changes that I made in the text and saves the text loaded in Page_Load.

This code doesn't show any database connection but you can understand what i'm talking about.

protected void Page_Load(object sender, EventArgs e)
    {           
        textboxTitle.Text = "This is the title of the news";       
        textboxBody.Text = "This is the body of the news ";        
    }

I load the page, make the changes in the text , and then click submit.

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        String title = textboxTitle.Text;        
        String body = textboxBody.Text;
        Response.Write("Title: " + title + " || ");
        Response.Write("Body: " + body );
    }

Nothing happens, the text in the textboxes is always the one I loaded in the page_load, how do I update the Text in the textboxes?


Page_Load runs every time your page is requested. If you're doing a one-time setup operation to populate the textboxes, don't repopulate them on every request.

You can do that by checking the IsPostBack flag to only execute the initialization code once.

protected void Page_Load(object sender, EventArgs e)
    {           
        if (!Page.IsPostBack)
         {
            textboxTitle.Text = "This is the title of the news";       
            textboxBody.Text = "This is the body of the news ";        
         }
    }


Sounds like you need to check the IsPostBack variable like so:

if(!Page.IsPostBack)
{
    textboxTitle.Text = "This is the title of the news";       
    textboxBody.Text = "This is the body of the news ";
}

That way, you only set te text of the controls on the first page request. Alternately, you can just specify this text on the HTML control itself, without using code in the .cs.

0

精彩评论

暂无评论...
验证码 换一张
取 消